#!/bin/sh

APP_HOME=$HOME

. "$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_UTIC_PTIS_SERVER) APP_VERSION="$APP_VER_UTIC_PTIS_SERVER" ;;
    *) echo "[ERROR] Unknown version variable: $APP_VERSION_VAR"; exit 1 ;;
  esac

  JAR_FILE="$APPS_DIR/$APP_NAME-$APP_VERSION.jar"
  PID_FILE="$PID_DIR/$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
    utic-ptis-server) JAVA_OPTS="$JAVA_OPTS $JAVA_OPTS_HEAPDUMP" ;;
    *) echo "[ERROR] Unknown app name: $APP_NAME"; exit 1 ;;
  esac

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

  ps -eaf | grep java | grep -v grep | grep -v tail
  echo ""
}

case "$1" in
  utic-ptis-server)
    start_app "$1"
    ;;
  *)
    for APP_NAME in $APP_LIST; do
      start_app "$APP_NAME"
    done
    ;;
esac

