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

[[ $# -eq 2 ]] || { echo "usage: web-preflight RELEASE PAGES_DIR" >&2; exit 2; }
release="$(realpath -e "$1")"
pages_dir="$(realpath -e "$2")"
entry="$release/server/entry.mjs"
node_bin="${OVERDECK_WEB_NODE_BIN:-/usr/bin/node}"
collector_url="${OVERDECK_COLLECTOR_URL:-http://127.0.0.1:31338}"
watchdog="${OVERDECK_WEB_WATCHDOG_BIN:-$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/web-watchdog.sh}"
log_file="${OVERDECK_WEB_PREFLIGHT_LOG:-$(mktemp)}"
child_pid=""
child_start=""

child_matches() {
  [[ -n "$child_pid" && -r "/proc/$child_pid/stat" && -r "/proc/$child_pid/cmdline" ]] || return 1
  [[ "$(cut -d ' ' -f 22 "/proc/$child_pid/stat")" == "$child_start" ]] || return 1
  tr '\0' '\n' <"/proc/$child_pid/cmdline" | grep -Fxq "$entry"
}

cleanup() {
  if child_matches; then
    kill "$child_pid" 2>/dev/null || true
    wait "$child_pid" 2>/dev/null || true
  fi
}
trap cleanup EXIT INT TERM HUP

port="$(python3 - <<'PY'
import socket
with socket.socket() as sock:
    sock.bind(("127.0.0.1", 0))
    print(sock.getsockname()[1])
PY
)"

(
  cd "$release"
  HOST=127.0.0.1 PORT="$port" OVERDECK_CONFIG_DIR="$HOME/.config/overdeck" \
    COLLECTOR_URL="$collector_url" exec "$node_bin" "$entry"
) >"$log_file" 2>&1 &
child_pid=$!
for _ in {1..50}; do
  kill -0 "$child_pid" 2>/dev/null || break
  child_start="$(cut -d ' ' -f 22 "/proc/$child_pid/stat" 2>/dev/null || true)"
  [[ -n "$child_start" ]] && child_matches && break
  child_start=""
  sleep 0.02
done
[[ -n "$child_start" ]] && child_matches || { echo "preflight child failed identity check" >&2; exit 1; }

for _ in {1..20}; do
  if OVERDECK_WEB_URL="http://127.0.0.1:${port}" OVERDECK_WEB_PAGES_DIR="$pages_dir" \
    "$watchdog" sweep >/dev/null 2>&1; then
    exit 0
  fi
  child_matches || break
  sleep 1
done
echo "staged release failed route sweep; log: $log_file" >&2
exit 1
