#!/usr/bin/env bash
# Run on Gentoo FE as root — proxy /v0/ota/ to BE listen 80 (static OTA tree).
# Superseded by consolidated apps.conf (nginx/fe/apps.conf + fe-nginx-apps-consolidation.patch).
set -euo pipefail

REPO_ROOT="$(cd "$(dirname "$0")/../../../.." && pwd)"
SNIPPET_FILE="$REPO_ROOT/examples/crash_reporter/backend/nginx.fe-ota.snippet"
NGINX_CONF="${1:-/etc/nginx/nginx.conf}"

if [[ ! -f "$NGINX_CONF" ]]; then
  echo "Usage: $0 [path/to/nginx.conf]" >&2
  exit 1
fi

if grep -q 'location /v0/ota/' "$NGINX_CONF"; then
  echo "$NGINX_CONF already has location /v0/ota/"
  nginx -t
  rc-service nginx reload
  exit 0
fi

python3 - "$NGINX_CONF" "$SNIPPET_FILE" << 'PY'
import sys
from pathlib import Path

path = Path(sys.argv[1])
snippet_path = Path(sys.argv[2])
snippet = snippet_path.read_text()
# Strip comment header lines; keep tab-indented location block only.
lines = []
for line in snippet.splitlines():
    if line.startswith("#") or not line.strip():
        continue
    lines.append(line)
block = "\n".join(lines) + "\n"
text = path.read_text()
needles = [
    "\t\tlocation /app/androidcast_project/ {\n",
    "\t\tlocation /app/androidcast_project/crashes/ {\n",
]
idx = -1
for needle in needles:
    idx = text.find(needle)
    if idx >= 0:
        break
if idx < 0:
    raise SystemExit("Could not find androidcast location block in nginx.conf — add nginx.fe-ota.snippet manually")
path.write_text(text[:idx] + block + text[idx:])
print(f"Patched {path} with /v0/ota/ proxy → BE :80")
PY

nginx -t
rc-service nginx reload

echo
echo "=== Verify ==="
curl -sS -o /dev/null -w 'public OTA HTTP %{http_code}\n' \
  'https://apps.f0xx.org/v0/ota/channel/stable.json' || true
