#!/usr/bin/env bash
# Replace BE apps.conf listen-80 block from repo fragment (run on machine with BE mount write access).
set -euo pipefail
REPO_ROOT="$(cd "$(dirname "$0")/../../../.." && pwd)"
EXAMPLES="$REPO_ROOT/examples"
FRAG="$EXAMPLES/crash_reporter/backend/nginx.apps-port80.fragment"
APPS_CONF="${1:-$REPO_ROOT/tmp/BE_alpine/etc/nginx/conf.d/apps.conf}"
if [[ ! -f "$FRAG" || ! -f "$APPS_CONF" ]]; then
  echo "Usage: $0 [path/to/apps.conf]" >&2
  exit 1
fi
python3 - "$FRAG" "$APPS_CONF" << 'PY'
import sys
from pathlib import Path
frag, apps_path = map(Path, sys.argv[1:3])
text = apps_path.read_text()
start = text.index("server {\n\tlisten 80;")
end = text.index("\n}\n\n\nserver {\n\tlisten 443")
apps_path.write_text(text[:start] + frag.read_text().strip() + text[end:])
print(f"Updated listen 80 in {apps_path}")
PY
