#!/bin/sh

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

. "$APP_HOME/conf/setenv.sh"

PID_SUFFIX=".pid"

stop_app() {
  APP_NAME=$1
  PID_FILE="$BIN_DIR/conf/$APP_NAME$PID_SUFFIX"

  if [ ! -f "$PID_FILE" ]; then
    echo "[WARN] $APP_NAME is not running (no PID file)"
    return
  fi

  PID=$(cat "$PID_FILE")
  if ! ps -p "$PID" > /dev/null 2>&1; then
    echo "[WARN] $APP_NAME: PID file exists but no process. Removing stale file."
    rm -f "$PID_FILE"
    return
  fi

  echo "[INFO] $APP_NAME: Sending SIGTERM to PID $PID"
  kill -15 "$PID"

  for i in $(seq 0 12); do
    sleep 1
    if ! ps -p "$PID" > /dev/null 2>&1; then
      echo "[INFO] $APP_NAME stopped gracefully."
      rm -f "$PID_FILE"
      return
    fi
    echo "[INFO] $APP_NAME stopping..."
  done

  echo "[INFO] $APP_NAME: Force killing PID $PID"
  kill -9 "$PID"
  rm -f "$PID_FILE"
  echo "[INFO] Cleanup complete."
}

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

echo ""
echo "[INFO] Remaining Java processes:"
ps -eaf | grep java | grep jar | grep rota-local- | grep -v grep
