#!/usr/bin/env bash
# Linux/Docker only. A failed migration deliberately leaves writers stopped.
set -euo pipefail
cd "$(dirname "$(realpath "$0")")"
backup_root=${1:?Usage: stage.sh /absolute/private/backup-root}
python3 release_audit.py
compose=(docker compose --env-file .env.server -f compose.yaml)
"${compose[@]}" config --quiet
"${compose[@]}" build web worker match-worker friendly-worker metrics
"${compose[@]}" --profile setup build frontend-build
"${compose[@]}" up -d db cache clamav
"${compose[@]}" run --rm --no-deps web python manage.py shell -c "from django.db import connection; assert connection.settings_dict['NAME'].startswith('ftg2_beta_')"
# Keep incoming requests, world scheduler and all writers stopped through migration.
bash backup.sh "$backup_root" leave-stopped
"${compose[@]}" run --rm --no-deps web python manage.py migrate --noinput
"${compose[@]}" run --rm --no-deps web python manage.py prepare_game_world
"${compose[@]}" run --rm --no-deps web python manage.py collectstatic --noinput
"${compose[@]}" --profile setup run --rm frontend-build
"${compose[@]}" --profile monitoring up -d web worker match-worker friendly-worker infrastructure-beat metrics prometheus
ready=0
for attempt in $(seq 1 30); do
  if "${compose[@]}" exec -T web python -c 'import os; from urllib.request import Request,urlopen; r=urlopen(Request("http://127.0.0.1:8000/health/ready/",headers={"Host":os.environ["DJANGO_ALLOWED_HOSTS"].split(",")[0].strip(),"X-Forwarded-Proto":"https"}),timeout=3); assert r.status==200'; then ready=1; break; fi
  sleep 2
done
[[ "$ready" = 1 ]] || { echo 'Readiness failed; inspect logs before enabling the world scheduler' >&2; exit 1; }
"${compose[@]}" exec -T web python manage.py release_security_check
"${compose[@]}" exec -T web python manage.py runtime_preflight --production
"${compose[@]}" exec -T web python manage.py verify_full_system --production --broker-roundtrip
"${compose[@]}" up -d caddy
echo 'Local staging checks passed. Validate external HTTPS, email, upload scanning, backup restoration and Linux worker-crash drills before opening access.'
echo 'World scheduler and token bridge remain stopped; enabling them requires their separate acceptance checks.'
