#!/usr/bin/env bash
# Waltermart kiosk (RB-01, critical): replace the keys that were exposed earlier.
#   1. a NEW "waltermart" key in the API's API_CLIENT_KEYS (backup kept), API redeployed
#   2. the same key in this app's .env (SOLAROPS_CLIENT_KEY); the old SOLAROPS_HMAC_SECRET line removed
#   3. a NEW CACHE_CLEAR_TOKEN
#   4. .env made root-only (read by docker compose on the host), container rebuilt, checked.
#      config/config.json is NOT made root-only: it is copied into the image and read by the
#      app as user "node"; 600 there stops the app (EACCES, outage 2026-11-09 10:26-10:30).
#   5. the two new values written to /root/waltermart-new-keys.env (root-only) so you can copy them to
#      MonitoringWM with scp. Delete that file after. Nothing is printed to the screen.
# Run on SolarOps-VM as root. Rollback: the backups it prints, then redeploy the API and this app.
set -euo pipefail
[ "$(id -u)" = 0 ] || { echo "Run as root (sudo -i)."; exit 1; }
APP=${APP:-/var/www/html/waltermart_dashboard_v2}
API_ENV=${API_ENV:-/root/solaredge-api.env}
API_REPO=${API_REPO:-/var/www/html/solaredge_api}
BK="/root/hardening-backups/waltermart-keys-$(date +%Y%m%d-%H%M%S)"; mkdir -p "$BK"; chmod 700 /root/hardening-backups "$BK"
cp -p "$API_ENV" "$BK/solaredge-api.env"; cp -p "$APP/.env" "$BK/waltermart.env"

KEY=$(openssl rand -hex 32); TOKEN=$(openssl rand -hex 24)

# 1. API side
CLIENT_KEY="$KEY" python3 - "$API_ENV" <<'PY'
import json, os, sys
p = sys.argv[1]; lines = open(p).read().splitlines()
keys = {}
for l in lines:
    if l.startswith("API_CLIENT_KEYS="): keys = json.loads(l.split("=", 1)[1] or "{}") or {}
keys["waltermart"] = os.environ["CLIENT_KEY"]
out = [l for l in lines if not l.startswith("API_CLIENT_KEYS=")] + ["API_CLIENT_KEYS=" + json.dumps(keys, separators=(",", ":"))]
open(p, "w").write("\n".join(out) + "\n")
PY
bash "$API_REPO/deploy/deploy_vm.sh"

# 2-3. App side
CLIENT_KEY="$KEY" TOKEN="$TOKEN" python3 - "$APP/.env" <<'PY'
import os, sys
p = sys.argv[1]; lines = open(p).read().splitlines()
drop = ("SOLAROPS_CLIENT_ID=", "SOLAROPS_CLIENT_KEY=", "SOLAROPS_HMAC_SECRET=", "CACHE_CLEAR_TOKEN=")
out = [l for l in lines if not l.startswith(drop)]
out += ["SOLAROPS_CLIENT_ID=waltermart", "SOLAROPS_CLIENT_KEY=" + os.environ["CLIENT_KEY"], "CACHE_CLEAR_TOKEN=" + os.environ["TOKEN"]]
open(p, "w").write("\n".join(out) + "\n")
PY
chmod 600 "$APP/.env"; [ -f "$APP/config/config.json" ] && chmod 644 "$APP/config/config.json"
(umask 077; printf 'SOLAROPS_CLIENT_ID=waltermart\nSOLAROPS_CLIENT_KEY=%s\nCACHE_CLEAR_TOKEN=%s\n' "$KEY" "$TOKEN" > /root/waltermart-new-keys.env)
unset KEY TOKEN

# 4. Rebuild and check
cd "$APP" && docker compose up -d --build
for _ in $(seq 1 30); do curl -fsS http://127.0.0.1:3000/healthz >/dev/null 2>&1 && break; sleep 2; done
code=$(curl -s -o /dev/null -w '%{http_code}' http://127.0.0.1:3000/healthz || true)
echo "healthz: $code   (expect 200)"
if [ "$code" != 200 ]; then
  docker logs --tail 15 waltermart-kiosk 2>&1 | grep -viE 'key|secret|token' || true
  echo "The app did not come up: restoring the previous .env and rebuilding (the API keeps the new key; harmless)."
  cp -p "$BK/waltermart.env" "$APP/.env"; (cd "$APP" && docker compose up -d --build); exit 1
fi
echo "fleet:   $(curl -s -o /dev/null -w '%{http_code}' http://127.0.0.1:3000/api/fleet)   (expect 200: the API accepts the new key)"
echo "Backups: $BK"
echo "MonitoringWM: scp /root/waltermart-new-keys.env <MonitoringWM>:/root/  then on it:"
echo "  put those 3 lines in $APP/.env (remove SOLAROPS_HMAC_SECRET), chmod 600 .env, docker compose up -d --build,"
echo "  and delete /root/waltermart-new-keys.env on both machines."
