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

run=false
yes=false
for arg in "$@"; do
  case "$arg" in
    --run) run=true ;;
    --yes) yes=true ;;
    *) echo "unknown argument: $arg" >&2; exit 2 ;;
  esac
done

if [[ "$run" != true ]]; then
  cat <<'TXT'
Dry run only. This proof runs entirely on an authorized Linux build/test host:
  1. creates a temporary user-local PostgreSQL cluster,
  2. starts a real DBOS workflow and waits until it is durably blocked on recv,
  3. abruptly exits the DBOS process with code 137 without DBOS shutdown,
  4. restarts DBOS and proves recovery/resume,
  5. proves retry behavior and duplicate workflow-start idempotency,
  6. proves a checkpointed external side-effect marker was not repeated,
  7. proves cancellation persists,
  8. starts DBOS a third time and proves terminal result persistence,
  9. removes the temporary PostgreSQL cluster/state.

Run intentionally with:
  bash tools/preflight/dbos-live-proof.sh --run [--yes]
TXT
  exit 0
fi

repo="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
node_script="$repo/packages/providers/workflow-dbos/test/live-runtime-proof.mjs"
[[ -f "$node_script" ]] || { echo "missing DBOS live proof worker" >&2; exit 2; }

pg_bin="${AWP_POSTGRES_BIN:-/usr/lib/postgresql/17/bin}"
for binary in initdb pg_ctl createdb; do
  [[ -x "$pg_bin/$binary" ]] || { echo "$pg_bin/$binary required" >&2; exit 2; }
done
command -v node >/dev/null 2>&1 || { echo "node required" >&2; exit 2; }

if [[ "$yes" != true ]]; then
  read -r -p "Run bounded temporary PostgreSQL + DBOS crash/restart proof on this host? [y/N] " answer
  [[ "$answer" =~ ^[Yy]$ ]] || exit 3
fi

tmp="$(mktemp -d /tmp/awp-dbos-live.XXXXXX)"
pgdata="$tmp/pgdata"
state="$tmp/state"
mkdir -p "$state"
port="$(python3 - <<'PY'
import socket
s=socket.socket()
s.bind(('127.0.0.1',0))
print(s.getsockname()[1])
s.close()
PY
)"
workflow_id="awp-live-$(date +%s)-$$"
start_log="$tmp/start.log"
resume_log="$tmp/resume.log"
inspect_log="$tmp/inspect.log"
postgres_started=false

cleanup(){
  if [[ "$postgres_started" == true ]]; then
    "$pg_bin/pg_ctl" -D "$pgdata" -m fast -w stop >/dev/null 2>&1 || true
  fi
  rm -rf "$tmp"
}
trap cleanup EXIT

"$pg_bin/initdb" -D "$pgdata" --auth=trust --no-locale >/dev/null
"$pg_bin/pg_ctl" -D "$pgdata" -o "-F -p $port -h 127.0.0.1 -k $tmp" -w start >/dev/null
postgres_started=true
"$pg_bin/createdb" -h 127.0.0.1 -p "$port" awp_dbos
url="postgresql://$(id -un)@127.0.0.1:$port/awp_dbos"

printf 'host=%s\npostgresPort=%s\nworkflowId=%s\n' "$(hostname)" "$port" "$workflow_id"

node_cmd=(node)
current_node="$(node --version 2>/dev/null || true)"
if [[ "$current_node" != v22.* && -x "$HOME/.local/bin/mise" ]]; then
  node_cmd=("$HOME/.local/bin/mise" x node@22 -- node)
fi
printf 'node=%s\n' "$("${node_cmd[@]}" --version)"

set +e
"${node_cmd[@]}" "$node_script" start "$url" "$state" "$workflow_id" >"$start_log" 2>&1
start_status=$?
set -e
cat "$start_log"
[[ "$start_status" -eq 137 ]] || { echo "DBOS worker did not terminate at the deliberate abrupt-restart point (status=$start_status)" >&2; exit 4; }
[[ -f "$state/ready" ]] || { echo "DBOS workflow never reached durable ready point" >&2; exit 5; }
echo "durableReady=$(cat "$state/ready")"
echo "processCrash=abrupt-exit-137-without-DBOS-shutdown"

"${node_cmd[@]}" "$node_script" resume "$url" "$state" "$workflow_id" >"$resume_log" 2>&1 || {
  echo "DBOS recovery/resume proof failed" >&2
  cat "$resume_log" >&2
  exit 6
}
cat "$resume_log"

"${node_cmd[@]}" "$node_script" inspect "$url" "$state" "$workflow_id" >"$inspect_log" 2>&1 || {
  echo "DBOS terminal persistence inspection failed" >&2
  cat "$inspect_log" >&2
  exit 7
}
cat "$inspect_log"

echo "PASS: real DBOS/PostgreSQL crash-restart-resume, retry, cancel, duplicate-start idempotency, side-effect checkpointing and terminal-result persistence proved."
