#!/usr/bin/env bash
# Waltermart kiosk: host nginx hardening on SolarOps-VM (RB-06, RB-27). Safe to run twice.
# Touches ONLY the "location ^~ /waltermart-kiosk/" block and conf.d/waltermart.conf.
#   - sends the real client address (X-Real-IP / X-Forwarded-For). Without it every kiosk
#     looks like the same Docker address, so the app's per-IP limit is shared by all (RB-06)
#   - per-IP rate limit at nginx, 429 when exceeded (RB-27)
# HSTS is already sent by the app (max-age=31536000), so it is not added here.
# Backs up first, runs nginx -t, and restores the backup automatically if the test fails.
# Rollback later:  bash waltermart-nginx.sh --rollback
set -euo pipefail
[ "$(id -u)" = 0 ] || { echo "Run as root (sudo -i)."; exit 1; }
SITE=${SITE:-/etc/nginx/sites-available/solarops}
CONF=${CONF:-/etc/nginx/conf.d/waltermart.conf}
BKROOT=/root/hardening-backups; mkdir -p "$BKROOT"; chmod 700 "$BKROOT"

if [ "${1:-}" = "--rollback" ]; then
  last=$(ls -1d "$BKROOT"/waltermart-nginx-* 2>/dev/null | tail -1) || true
  [ -n "$last" ] || { echo "No backup found in $BKROOT."; exit 1; }
  cp -p "$last/solarops" "$SITE"; rm -f "$CONF"; [ -f "$last/conf" ] && cp -p "$last/conf" "$CONF"
  nginx -t && systemctl reload nginx && echo "Restored $last."; exit 0
fi

BK="$BKROOT/waltermart-nginx-$(date +%Y%m%d-%H%M%S)"; mkdir -p "$BK"
cp -p "$SITE" "$BK/solarops"; [ -f "$CONF" ] && cp -p "$CONF" "$BK/conf"
restore() { cp -p "$BK/solarops" "$SITE"; rm -f "$CONF"; [ -f "$BK/conf" ] && cp -p "$BK/conf" "$CONF"; echo "nginx -t failed: restored the backup ($BK). Nothing was reloaded."; }

cat > "$CONF" <<'EOF'
# Waltermart kiosk rate limit zone (RB-27), used in the /waltermart-kiosk/ location.
limit_req_zone $binary_remote_addr zone=waltermart:10m rate=10r/s;
EOF

python3 - "$SITE" <<'PY'
import sys
path = sys.argv[1]
s = open(path).read()
head = "    location ^~ /waltermart-kiosk/ {"
start = s.index(head)
end = s.index("\n    }", start)
block = s[start:end]
if "# hardening-waltermart" in block:
    print("Already applied; nothing to change in the site file."); sys.exit(0)
block = block.replace(head, head +
    "\n        # hardening-waltermart (RB-06, RB-27): real client IP for the app, rate limit 10/s per IP"
    "\n        proxy_set_header X-Real-IP $remote_addr;"
    "\n        proxy_set_header X-Forwarded-For $remote_addr;"
    "\n        limit_req zone=waltermart burst=60 nodelay;"
    "\n        limit_req_status 429;", 1)
s = s[:start] + block + s[end:]
open(path, "w").write(s)
print("Updated the /waltermart-kiosk/ location.")
PY

if ! nginx -t; then restore; exit 1; fi
[ -n "${NO_RELOAD:-}" ] || systemctl reload nginx
echo "Done. Backup: $BK"
echo "Check:  curl -s -o /dev/null -w '%{http_code}\n' https://solarops.nsr.com.ph/waltermart-kiosk/healthz"
