#!/bin/sh

set -eu

SCRIPT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
PROJECT_ROOT="${PROJECT_ROOT:-$(CDPATH= cd -- "$SCRIPT_DIR/../../.." && pwd)}"
RUNNER_SCRIPT="${SERVER_COMMAND_RUNNER_SCRIPT:-$PROJECT_ROOT/scripts/run-server-command-runner.mjs}"
RUNNER_NODE_BIN="${SERVER_COMMAND_RUNNER_NODE_BIN:-node}"
SUPERVISOR_SCRIPT="${SERVER_COMMAND_RUNNER_SUPERVISOR_SCRIPT:-$PROJECT_ROOT/scripts/server-command-runner-supervisor.sh}"
RUNNER_NVM_DIR="${SERVER_COMMAND_RUNNER_NVM_DIR:-$HOME/.nvm}"
RUNNER_HOST="${SERVER_COMMAND_RUNNER_HOST:-0.0.0.0}"
RUNNER_PORT="${SERVER_COMMAND_RUNNER_PORT:-3211}"
RUNNER_ACCESS_TOKEN="${SERVER_COMMAND_RUNNER_ACCESS_TOKEN:-local-server-command-runner}"
RUNNER_LOG_FILE="${SERVER_COMMAND_RUNNER_LOG_FILE:-/tmp/server-command-runner.log}"
RUNNER_HEARTBEAT_FILE="${SERVER_COMMAND_RUNNER_HEARTBEAT_FILE:-$PROJECT_ROOT/.server-command-runner-heartbeat.json}"
SUPERVISOR_PID_FILE="${SERVER_COMMAND_RUNNER_SUPERVISOR_PID_FILE:-/tmp/server-command-runner-supervisor.pid}"
RUNNER_SCRIPT_BASENAME=$(basename "$RUNNER_SCRIPT")

if [ "$RUNNER_NODE_BIN" = "node" ] && [ -s "$RUNNER_NVM_DIR/nvm.sh" ]; then
  # Fresh-PC shells often miss the nvm-managed Node.js path in non-login execution.
  . "$RUNNER_NVM_DIR/nvm.sh"
  if command -v node >/dev/null 2>&1; then
    RUNNER_NODE_BIN=$(command -v node)
  fi
fi

if ! command -v "$RUNNER_NODE_BIN" >/dev/null 2>&1; then
  echo "node runtime not found: $RUNNER_NODE_BIN" >&2
  exit 1
fi

if [ ! -x "$SUPERVISOR_SCRIPT" ]; then
  chmod +x "$SUPERVISOR_SCRIPT"
fi

if [ -f "$SUPERVISOR_PID_FILE" ]; then
  SUPERVISOR_PID=$(cat "$SUPERVISOR_PID_FILE" 2>/dev/null || true)
  if [ -n "${SUPERVISOR_PID:-}" ] && kill -0 "$SUPERVISOR_PID" 2>/dev/null; then
    kill -HUP "$SUPERVISOR_PID"
    echo "server-command-runner reload requested"
    exit 0
  fi

  rm -f "$SUPERVISOR_PID_FILE"
fi

LEGACY_RUNNER_PIDS=$(ps -ef | grep "$RUNNER_SCRIPT_BASENAME" | grep -v grep | awk '{print $2}' || true)
if [ -n "$LEGACY_RUNNER_PIDS" ]; then
  kill $LEGACY_RUNNER_PIDS || true
  sleep 1
fi

setsid env \
  PROJECT_ROOT="$PROJECT_ROOT" \
  SERVER_COMMAND_RUNNER_HOST="$RUNNER_HOST" \
  SERVER_COMMAND_RUNNER_PORT="$RUNNER_PORT" \
  SERVER_COMMAND_RUNNER_ACCESS_TOKEN="$RUNNER_ACCESS_TOKEN" \
  SERVER_COMMAND_RUNNER_HEARTBEAT_FILE="$RUNNER_HEARTBEAT_FILE" \
  SERVER_COMMAND_RUNNER_SCRIPT="$RUNNER_SCRIPT" \
  SERVER_COMMAND_RUNNER_NODE_BIN="$RUNNER_NODE_BIN" \
  SERVER_COMMAND_RUNNER_SUPERVISOR_PID_FILE="$SUPERVISOR_PID_FILE" \
  "$SUPERVISOR_SCRIPT" >>"$RUNNER_LOG_FILE" 2>&1 </dev/null &

echo "server-command-runner restart requested"
