#!/bin/sh

APP_NAME=cmvr-iot-admin.jar
APP_JAR=cmvr-iot-admin/target/cmvr-iot-admin.jar
[ -f "$APP_NAME" ] && APP_JAR=$APP_NAME
JVM_OPTS="-Dname=$APP_NAME -Duser.timezone=Asia/Shanghai -Xms512m -Xmx1024m -XX:MetaspaceSize=128m -XX:MaxMetaspaceSize=512m -XX:+HeapDumpOnOutOfMemoryError -XX:+UseParallelGC"
LOG_DIR="$(pwd)/logs"
LOG_FILE="$LOG_DIR/$APP_NAME.log"

find_pid() {
    ps -ef | grep java | grep "$APP_NAME" | grep -v grep | awk '{print $2}'
}

start() {
    if [ ! -f "$APP_JAR" ]; then
        echo "Missing $APP_JAR. Run mvn clean package -DskipTests first."
        exit 1
    fi
    PID=$(find_pid)
    if [ -n "$PID" ]; then
        echo "$APP_NAME is already running with PID $PID."
        return
    fi
    mkdir -p "$LOG_DIR"
    nohup java $JVM_OPTS -jar "$APP_JAR" >> "$LOG_FILE" 2>&1 &
    echo "Started $APP_NAME with PID $!."
}

stop() {
    PID=$(find_pid)
    if [ -z "$PID" ]; then
        echo "$APP_NAME is not running."
        return
    fi
    kill -TERM $PID
    echo "Stopped $APP_NAME."
}

status() {
    PID=$(find_pid)
    if [ -n "$PID" ]; then
        echo "$APP_NAME is running with PID $PID."
    else
        echo "$APP_NAME is not running."
    fi
}

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