#!/usr/bin/env bash
# Idempotent seed for the cpanel_import.* block in /docker/whp/settings.json.
#
# Defaults the execution_mode to "direct" so existing servers keep their
# current behavior on update. Operators flip to "sanitization-container"
# from Server Settings -> Security -> "cPanel Import: Sanitization Sandbox"
# after the cpanel-importer image is in the registry and pulled on the host.
#
# Re-running is a no-op when the cpanel_import key already exists.
set -euo pipefail

SETTINGS=/docker/whp/settings.json
if [ ! -f "$SETTINGS" ]; then
    echo "settings.json not present - skipping cpanel_import seed"
    exit 0
fi

command -v jq >/dev/null 2>&1 || { echo "FATAL: jq required" >&2; exit 1; }

read -r -d '' DEFAULTS <<'EOF' || true
{
  "execution_mode": "direct",
  "image": "repo.anhonesthost.net/cloud-hosting-platform/cpanel-importer:latest",
  "image_pull_policy": "missing",
  "container_timeout_seconds": 7200,
  "memory_limit": "2g",
  "cpu_limit": "2",
  "fall_back_to_direct_on_image_unavailable": true,
  "quarantine_retention_days": 90
}
EOF

NEW=$(jq --argjson d "$DEFAULTS" 'if has("cpanel_import") then . else .cpanel_import = $d end' "$SETTINGS")

TMP=$(mktemp)
trap 'rm -f "$TMP"' EXIT

printf '%s\n' "$NEW" > "$TMP"
chmod --reference="$SETTINGS" "$TMP" 2>/dev/null || chmod 0600 "$TMP"
chown --reference="$SETTINGS" "$TMP" 2>/dev/null || true
mv "$TMP" "$SETTINGS"

echo "cpanel_import settings seeded (or already present)"
