#!/bin/sh
# Container supervisor. Busybox ash (node:*-alpine) has no reliable `wait -n`,
# so we poll with `kill -0` instead. nginx is the critical process — if it dies
# the container exits (non-zero) for the orchestrator to restart. The
# regenerator is a sidecar: if it dies we restart just it, so nginx keeps
# serving and any already-applied live patches survive.

start_regen() {
  node /app/regenerator/server.js &
  REGEN_PID=$!
}

shutdown() {
  kill "$REGEN_PID" "$NGINX_PID" 2>/dev/null
  exit 0
}
trap shutdown TERM INT

start_regen

nginx -g 'daemon off;' &
NGINX_PID=$!

while kill -0 "$NGINX_PID" 2>/dev/null; do
  if ! kill -0 "$REGEN_PID" 2>/dev/null; then
    echo "[start] regenerator exited — restarting sidecar"
    start_regen
  fi
  sleep 2
done

echo "[start] nginx exited — stopping container"
kill "$REGEN_PID" 2>/dev/null || true
exit 1
