#!/bin/sh

APP_HOME=$HOME

. "$APP_HOME/conf/setenv.sh"

stop_app() {
  APP_NAME=$1
  PID_FILE="$PID_DIR/$APP_NAME.pid"

  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"
  kill -15 "$PID" >/dev/null 2>&1

  echo "[INFO] $APP_NAME: Terminate waiting..."
  sleep 5

  i=0
  while [ "$i" -le 8 ]; 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..."
    i=`expr "$i" + 1`
  done

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

case "$1" in
  utic-pits-server)
    stop_app "$1"
    ;;
  *)
    for APP in $APP_LIST; do
      stop_app "$APP"
    done
    ;;
esac

echo ""
echo "[INFO] Remaining Java processes:"
ps -eaf | grep java | grep jar | grep utic-ptis-server | grep -v grep
