#!/usr/bin/env bash
set -euo pipefail

ROOT_DIR="/Users/ashwin/workspace/nxtgauge-admin-solid"
PID_FILE="/tmp/nxtgauge-admin-9202.pid"
APP_LOG="/tmp/nxtgauge-admin-9202.log"
APP_URL="http://127.0.0.1:9202/admin/external-dashboard-management"

kill_listeners() {
  lsof -tiTCP:9202 -sTCP:LISTEN | xargs -r kill -9 || true
}

start() {
  if [[ -f "$PID_FILE" ]]; then
    old_pid="$(cat "$PID_FILE" || true)"
    if [[ -n "${old_pid:-}" ]] && kill -0 "$old_pid" 2>/dev/null; then
      if curl -fsS -m 3 "$APP_URL" >/dev/null 2>&1; then
        echo "admin-9202 already running (pid $old_pid)"
        echo "url: $APP_URL"
        return 0
      fi
      kill -9 "$old_pid" || true
    fi
    rm -f "$PID_FILE"
  fi

  pkill -f "admin-9202-daemon.sh" || true
  pkill -f ".output/server/index.mjs" || true
  kill_listeners

  nohup /bin/zsh -lc "cd '$ROOT_DIR' && HOST=0.0.0.0 PORT=9202 node .output/server/index.mjs" >>"$APP_LOG" 2>&1 &
  new_pid=$!
  echo "$new_pid" > "$PID_FILE"

  for _ in {1..30}; do
    if curl -fsS -m 3 "$APP_URL" >/dev/null 2>&1; then
      echo "admin-9202: running (pid $new_pid)"
      echo "url: $APP_URL"
      return 0
    fi
    sleep 1
  done

  echo "admin-9202 failed to become healthy"
  tail -n 80 /tmp/nxtgauge-admin-9202.log || true
  exit 1
}

stop() {
  if [[ -f "$PID_FILE" ]]; then
    pid="$(cat "$PID_FILE" || true)"
    if [[ -n "${pid:-}" ]] && kill -0 "$pid" 2>/dev/null; then
      kill -9 "$pid" || true
    fi
    rm -f "$PID_FILE"
  fi

  pkill -f "admin-9202-daemon.sh|.output/server/index.mjs" || true
  kill_listeners
  echo "admin-9202: stopped"
}

status() {
  app_state="stopped"
  app_pid=""
  if [[ -f "$PID_FILE" ]]; then
    app_pid="$(cat "$PID_FILE" || true)"
    if [[ -n "${app_pid:-}" ]] && kill -0 "$app_pid" 2>/dev/null; then
      app_state="running"
    fi
  fi

  if lsof -nP -iTCP:9202 -sTCP:LISTEN >/dev/null 2>&1; then
    echo "admin-9202: running"
    echo "process: $app_state${app_pid:+ (pid $app_pid)}"
    lsof -nP -iTCP:9202 -sTCP:LISTEN
    exit 0
  fi

  echo "admin-9202: stopped"
  echo "process: $app_state${app_pid:+ (pid $app_pid)}"
  exit 1
}

action="${1:-restart}"
case "$action" in
  start) start ;;
  stop) stop ;;
  restart) stop; start ;;
  status) status ;;
  *)
    echo "Usage: $0 [start|stop|restart|status]"
    exit 2
    ;;
esac
