#!/usr/bin/env bash
#
# Seed default ssl_renewal settings into /docker/whp/settings.json.
# Idempotent: only writes the block if it's not already present.
#
# Defaults for new installs:
#   orchestrator_enabled       = true   (the orchestrated renewal IS the renewal system; new installs get it on)
#   email_unreachable_enabled  = true
#   email_manual_review_enabled = true
#   email_recovered_enabled    = false  (recovery emails OFF — opt in after customer-noise testing)
#   email_dns_validation_enabled = true
#
# This script is idempotent: it only sets keys that aren't already present.
# Existing installs keep whatever the operator (or prior seed run) set.
# 2026-05-09 prod was seeded with orchestrator_enabled=false from an earlier
# version of this script; flip it via the server settings page UI when ready.

set -euo pipefail

SETTINGS="/docker/whp/settings.json"

if [ ! -f "${SETTINGS}" ]; then
    echo "WARN: ${SETTINGS} not found; skipping seed."
    exit 0
fi

python3 <<'PY'
import json
import sys
from pathlib import Path

p = Path("/docker/whp/settings.json")
data = json.loads(p.read_text())

defaults = {
    "orchestrator_enabled": True,
    "email_unreachable_enabled": True,
    "email_manual_review_enabled": True,
    "email_recovered_enabled": False,
    "email_dns_validation_enabled": True,
}

block = data.get("ssl_renewal")
if not isinstance(block, dict):
    block = {}

changed = False
for k, v in defaults.items():
    if k not in block:
        block[k] = v
        changed = True

if changed:
    data["ssl_renewal"] = block
    # Preserve formatting roughly: 4-space indent matches the existing file.
    p.write_text(json.dumps(data, indent=4) + "\n")
    print(f"Seeded ssl_renewal defaults: added keys {[k for k in defaults if k not in block or block[k] == defaults[k]]}")
else:
    print("ssl_renewal block already complete; nothing to seed.")
PY

echo "ssl_renewal settings seeded."
