#!/bin/sh

set -eu

PROJECT_ROOT="${PROJECT_ROOT:-$(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_PID_FILE="${SERVER_COMMAND_RUNNER_SUPERVISOR_PID_FILE:-/tmp/server-command-runner-supervisor.pid}"
CHILD_PID=""
STOP_REQUESTED="0"
RELOAD_REQUESTED="0"

log() {
  printf '[server-command-runner-supervisor] %s\n' "$*"
}

cleanup() {
  rm -f "$SUPERVISOR_PID_FILE"
}

start_child() {
  log "starting runner child"
  "$RUNNER_NODE_BIN" "$RUNNER_SCRIPT" &
  CHILD_PID=$!
}

request_reload() {
  RELOAD_REQUESTED="1"
  log "reload requested"
  if [ -n "$CHILD_PID" ]; then
    kill -TERM "$CHILD_PID" 2>/dev/null || true
  fi
}

request_stop() {
  STOP_REQUESTED="1"
  log "shutdown requested"
  if [ -n "$CHILD_PID" ]; then
    kill -TERM "$CHILD_PID" 2>/dev/null || true
  fi
}

trap 'request_reload' HUP
trap 'request_stop' INT TERM
trap 'cleanup' EXIT

printf '%s\n' "$$" >"$SUPERVISOR_PID_FILE"
cd "$PROJECT_ROOT"

while :; do
  start_child
  set +e
  wait "$CHILD_PID"
  EXIT_CODE=$?
  set -e
  CHILD_PID=""

  if [ "$STOP_REQUESTED" = "1" ]; then
    exit "$EXIT_CODE"
  fi

  if [ "$RELOAD_REQUESTED" = "1" ]; then
    RELOAD_REQUESTED="0"
    continue
  fi

  log "runner exited unexpectedly with code $EXIT_CODE; restarting in 2 seconds"
  sleep 2
done
