#!/usr/bin/env bash
# Run on Gentoo FE as root — wire build proxy like hub/crashes (BE :443).
set -euo pipefail

NGINX_CONF="/etc/nginx/nginx.conf"
APPS_CONF="/etc/nginx/apps.conf"
SNIPPET='		location /app/androidcast_project/build/ {
		 	proxy_pass https://artc0.intra.raptor.org/app/androidcast_project/build/;
		}
'

if grep -q 'androidcast_project/build/' "$NGINX_CONF"; then
  echo "nginx.conf already has androidcast_project/build/ location"
else
  if ! grep -q 'androidcast_project/crashes/' "$NGINX_CONF"; then
    echo "Cannot find crashes block in $NGINX_CONF — add build block manually after crashes." >&2
    exit 1
  fi
  python3 - "$NGINX_CONF" "$SNIPPET" << 'PY'
import sys
from pathlib import Path
path, snippet = Path(sys.argv[1]), sys.argv[2]
text = path.read_text()
needle = "\t\tlocation /app/androidcast_project/crashes/ {\n"
idx = text.find(needle)
if idx < 0:
    raise SystemExit("crashes location not found")
end = text.find("\n\t\t}", idx)
if end < 0:
    raise SystemExit("crashes block end not found")
end = text.find("\n", end + 1)
path.write_text(text[:end] + "\n" + snippet + text[end:])
print(f"Patched {path}")
PY
fi

if [[ -f "$APPS_CONF" ]]; then
  if grep -q 'proxy_pass http://artc0.intra.raptor.org:80' "$APPS_CONF" 2>/dev/null; then
    cp -a "$APPS_CONF" "${APPS_CONF}.bak.$(date +%Y%m%d%H%M%S)"
    sed -i 's|proxy_pass http://artc0.intra.raptor.org:80;|# DISABLED — use nginx.conf :443 upstream\n\t\t    # proxy_pass http://artc0.intra.raptor.org:80;|' "$APPS_CONF" || true
    echo "Commented stale :80 build proxy in $APPS_CONF (backup created)"
  fi
fi

nginx -t
rc-service nginx reload

echo
echo "=== FE localhost curl ==="
curl -sSI -H 'Host: apps.f0xx.org' 'http://127.0.0.1/app/androidcast_project/build/' -k 2>/dev/null \
  | grep -E 'HTTP|location|x-powered-by' || \
curl -sSI -H 'Host: apps.f0xx.org' 'https://127.0.0.1/app/androidcast_project/build/' -k \
  | grep -E 'HTTP|location|x-powered-by'

echo
echo "Public check:"
echo "  curl -sSI 'https://apps.f0xx.org/app/androidcast_project/build/' | grep -E 'HTTP|location|x-powered-by'"
