#!/bin/bash
# Default values
DEFAULT_APP_NAME="{project name 입력}"
DEFAULT_WAR_PATH="/data/webapps/$DEFAULT_APP_NAME/target/$DEFAULT_APP_NAME-0.0.1-SNAPSHOT.war"
DEFAULT_PID_FILE="/var/run/$DEFAULT_APP_NAME.pid"
DEFAULT_LOG_FILE="/var/log/$DEFAULT_APP_NAME.log"

# Use environment variables if set, otherwise use defaults
APP_NAME="${APP_NAME:-$DEFAULT_APP_NAME}"
WAR_PATH="${WAR_PATH:-$DEFAULT_WAR_PATH}"
PID_FILE="${PID_FILE:-$DEFAULT_PID_FILE}"
LOG_FILE="${LOG_FILE:-$DEFAULT_LOG_FILE}"
MVN_CMD="mvn clean package"

log() {
    echo "$(date '+%Y-%m-%d %H:%M:%S') - $1" >> $LOG_FILE
}

build() {
    log "Building $APP_NAME..."
    cd /data/webapps/$APP_NAME || { log "Failed to change directory to /data/webapps/$APP_NAME"; exit 1; }
    $MVN_CMD >> $LOG_FILE 2>&1
    if [ $? -ne 0 ]; then
        log "Build failed. Exiting."
        exit 1
    fi
    log "Build succeeded."
}

start() {
    if [ -f $PID_FILE ]; then
        log "$APP_NAME is already running."
        exit 1
    fi

    log "Starting $APP_NAME..."
    nohup java -jar $WAR_PATH >> $LOG_FILE 2>&1 &
    echo $! > $PID_FILE
    log "$APP_NAME started with PID $(cat $PID_FILE)."
}

stop() {
    if [ ! -f $PID_FILE ]; then
        log "$APP_NAME is not running."
        exit 1
    fi

    PID=$(cat $PID_FILE)
    log "Stopping $APP_NAME with PID $PID..."
    kill $PID
    rm $PID_FILE
    log "$APP_NAME stopped."
}

restart() {
    log "Restarting $APP_NAME..."
    stop
    start
}

case "$1" in
    build)
        build
        ;;
    start)
        start
        ;;
    stop)
        stop
        ;;
    restart)
        restart
        ;;
    *)
        log "Usage: $0 {build|start|stop|restart}"
        exit 1
esac

exit 0
