#!/usr/bin/env bash
# Build fe-nginx-apps-consolidation.patch from repo template vs tmp/FE_gentoo mirror.
set -euo pipefail

REPO_ROOT="$(cd "$(dirname "$0")/../../../.." && pwd)"
FE_MIRROR="${FE_MIRROR:-$REPO_ROOT/tmp/FE_gentoo/etc/nginx}"
TEMPLATE="$REPO_ROOT/examples/crash_reporter/backend/nginx/fe/apps.conf"
PATCH_OUT="$REPO_ROOT/examples/crash_reporter/backend/patches/fe-nginx-apps-consolidation.patch"

if [[ ! -f "$FE_MIRROR/nginx.conf" || ! -f "$FE_MIRROR/apps.conf" ]]; then
  echo "Missing FE mirror at $FE_MIRROR (sshfs tmp/FE_gentoo)" >&2
  exit 1
fi

WORK="$(mktemp -d)"
trap 'rm -rf "$WORK"' EXIT

cp "$FE_MIRROR/nginx.conf" "$WORK/nginx.conf.orig"
cp "$FE_MIRROR/apps.conf" "$WORK/apps.conf.orig"
cp "$TEMPLATE" "$WORK/apps.conf.new"

python3 - "$WORK/nginx.conf.orig" "$WORK/nginx.conf.new" << 'PY'
import sys
from pathlib import Path

src, dst = map(Path, sys.argv[1:3])
lines = src.read_text().splitlines(keepends=True)

start = None
for i, line in enumerate(lines):
    if line.strip() == "## -------------------------------------------------------------------------------":
        # Next non-empty should be server { listen 80 apps.f0xx.org
        for j in range(i + 1, min(i + 5, len(lines))):
            if "server_name apps.f0xx.org" in lines[j] or (
                j + 1 < len(lines) and "server_name apps.f0xx.org" in lines[j + 1]
            ):
                start = i
                break
        if start is not None:
            break

if start is None:
    raise SystemExit("Could not find apps.f0xx.org section start in nginx.conf")

# End at closing brace of 443 server: line that is only `\t}` or `        }` before blank line and http `}`
end = None
for i in range(len(lines) - 1, start, -1):
    if lines[i].strip() == "}":
        # http block ends with `}\n` then EOF; 443 server closes with `}\n` then `\n` then `}`
        if i + 1 < len(lines) and lines[i + 1].strip() == "":
            if i + 2 < len(lines) and lines[i + 2].strip() == "}":
                end = i
                break

if end is None:
    raise SystemExit("Could not find apps.f0xx.org section end in nginx.conf")

replacement = (
    "## -------------------------------------------------------------------------------\n"
    "## apps.f0xx.org — Android Cast (hub, crashes, graphs, build, OTA, git)\n"
    "\tinclude /etc/nginx/apps.conf;\n"
    "\n"
)
new_lines = lines[:start] + [replacement] + lines[end + 1 :]
dst.write_text("".join(new_lines))
print(f"nginx.conf: replaced lines {start + 1}–{end + 1} with include")
PY

mkdir -p "$(dirname "$PATCH_OUT")"
(
  cd "$WORK"
  diff -u apps.conf.orig apps.conf.new || true
  diff -u nginx.conf.orig nginx.conf.new || true
) > "$PATCH_OUT" || true

# Fix patch headers to use etc/nginx/ paths for clarity
sed -i 's|--- .*apps.conf.orig|--- a/etc/nginx/apps.conf|' "$PATCH_OUT"
sed -i 's|+++ .*apps.conf.new|+++ b/etc/nginx/apps.conf|' "$PATCH_OUT"
sed -i 's|--- .*nginx.conf.orig|--- a/etc/nginx/nginx.conf|' "$PATCH_OUT"
sed -i 's|+++ .*nginx.conf.new|+++ b/etc/nginx/nginx.conf|' "$PATCH_OUT"

cat > "$REPO_ROOT/examples/crash_reporter/backend/patches/fe-nginx-APPLY.md" << EOF
# FE nginx consolidation — review & apply

## What changes

- **\`/etc/nginx/apps.conf\`** becomes the full \`apps.f0xx.org\` vhost (HTTP redirect + HTTPS server + all Android Cast locations).
- **\`/etc/nginx/nginx.conf\`** drops inline \`apps.f0xx.org\` server blocks; adds one \`include /etc/nginx/apps.conf;\` at \`http\` level.

## New / consolidated paths in apps.conf

| Path | Upstream |
|------|----------|
| \`/v0/ota/\` | BE :80 (OTA) |
| \`/app/androidcast_project/build/\` | BE :80 |
| \`/app/androidcast_project/crashes/\` | BE :80 |
| \`/app/androidcast_project/graphs/\` | BE :80 (explicit) |
| \`/app/androidcast_project/\` | BE :80 (hub) |
| \`/app/androidcast_project/git/\` | BE :3000 (Gitea) |
| \`/\` (default) | BE :80 |

Canonical template: \`examples/crash_reporter/backend/nginx/fe/apps.conf\`

## Apply (on f0xx-monstro)

\`\`\`bash
cd /etc/nginx
cp -a apps.conf "apps.conf.bak.\$(date +%Y%m%d)"
cp -a nginx.conf "nginx.conf.bak.\$(date +%Y%m%d)"
# copy template from repo sync, or patch:
# patch -p1 < .../fe-nginx-apps-consolidation.patch
cp /path/to/android_cast/examples/crash_reporter/backend/nginx/fe/apps.conf apps.conf
# edit nginx.conf: replace apps.f0xx.org server {…} blocks with:
#   include /etc/nginx/apps.conf;
nginx -t && rc-service nginx reload
\`\`\`

## Verify

\`\`\`bash
curl -sS -o /dev/null -w 'hub %{http_code}\\n' https://apps.f0xx.org/app/androidcast_project/
curl -sS -o /dev/null -w 'ota %{http_code}\\n' https://apps.f0xx.org/v0/ota/channel/stable.json
curl -sS -o /dev/null -w 'build %{http_code}\\n' https://apps.f0xx.org/app/androidcast_project/build/
\`\`\`
EOF

echo "Wrote $PATCH_OUT"
echo "Wrote $REPO_ROOT/examples/crash_reporter/backend/patches/fe-nginx-APPLY.md"
