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

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

stop_server() {
  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

  lsof -tiTCP:9202 -sTCP:LISTEN | xargs -r kill -9 || true
}

status_server() {
  if lsof -nP -iTCP:9202 -sTCP:LISTEN >/dev/null 2>&1; then
    echo "admin-9202: running"
    lsof -nP -iTCP:9202 -sTCP:LISTEN
    exit 0
  fi
  echo "admin-9202: stopped"
  exit 1
}

start_server() {
  cd "$ROOT_DIR"

  if [[ ! -f ".output/server/index.mjs" ]]; then
    echo "Build output missing. Running build..."
    npm run build
  fi

  nohup env HOST=127.0.0.1 PORT=9202 node .output/server/index.mjs >"$LOG_FILE" 2>&1 &
  new_pid=$!
  echo "$new_pid" > "$PID_FILE"

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

  echo "admin-9202: failed to start"
  echo "Last log lines:"
  tail -n 40 "$LOG_FILE" || true
  exit 1
}

action="${1:-restart}"
case "$action" in
  restart)
    stop_server
    start_server
    ;;
  stop)
    stop_server
    echo "admin-9202: stopped"
    ;;
  status)
    status_server
    ;;
  *)
    echo "Usage: $0 [restart|stop|status]"
    exit 2
    ;;
esac
