#!/bin/sh

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
APP_HOME="$(dirname "$SCRIPT_DIR")"

. "$APP_HOME/conf/setenv.sh"

start_app() {
  APP_NAME="$1"

  APP_VERSION_VAR="APP_VER_$(echo "$APP_NAME" | tr '-' '_' | tr '[:lower:]' '[:upper:]')"

  case "$APP_VERSION_VAR" in
    APP_VER_ROTA_LOCAL_CLIENT) APP_VERSION="$APP_VER_ROTA_LOCAL_CLIENT" ;;
    APP_VER_ROTA_LOCAL_SERVER) APP_VERSION="$APP_VER_ROTA_LOCAL_SERVER" ;;
    APP_VER_MOCT_LOCAL_CLIENT) APP_VERSION="$APP_VER_MOCT_LOCAL_CLIENT" ;;
    *) echo "[ERROR] Unknown version variable: $APP_VERSION_VAR"; exit 1 ;;
  esac

  JAR_FILE="$APPS_DIR/$APP_NAME-$APP_VERSION.jar"
  PID_FILE="$BIN_DIR/conf/$APP_NAME.pid"

  if [ -f "$PID_FILE" ]; then
    PID=$(cat "$PID_FILE")
    if ps -p "$PID" > /dev/null 2>&1; then
      echo "[WARN] $APP_NAME is already running (PID: $PID)"
      return
    else
      echo "[INFO] Application PID file found. Cleaning: $PID_FILE"
      rm -f "$PID_FILE"
    fi
  fi

  case "$APP_NAME" in
    rota-local-client) JAVA_OPTS="$JAVA_OPTS_ROTA_LOCAL_CLIENT $JAVA_OPTS_HEAPDUMP" ;;
    rota-local-server) JAVA_OPTS="$JAVA_OPTS_ROTA_LOCAL_SERVER $JAVA_OPTS_HEAPDUMP" ;;
    moct-local-client) JAVA_OPTS="$JAVA_OPTS_MOCT_LOCAL_CLIENT $JAVA_OPTS_HEAPDUMP" ;;
    *) echo "[ERROR] Unknown app name: $APP_NAME"; exit 1 ;;
  esac

  echo "[INFO] Starting $APP_NAME..."
  nohup "$JAVA_BIN" $JAVA_OPTS -jar "$JAR_FILE" > /dev/null 2>&1 &
  echo "[INFO] $APP_NAME started with PID $(cat "$PID_FILE")"
}

case "$1" in
  rota-local-client | rota-local-server | moct-local-client)
    start_app "$1"
    ;;
  all)
    for APP_NAME in $APP_LIST; do
      start_app "$APP_NAME"
    done
    ;;
  *)
    echo "Usage: $0 {rota-local-client|rota-local-server|moct-local-client|all}"
    exit 1
    ;;
esac
