#!/usr/bin/env bash
# One-shot config migration for the Phase 2 remediation rename.
#
# Earlier the AI Monitor settings UI saved its toggles under
# [auto_remediation] but the engine read [remediation]. Phase 2 unifies
# both onto [remediation]. This shim:
#   - Copies any non-empty values from the legacy section to the canonical
#     one (without overwriting fresh keys already saved post-update).
#   - Renames mismatched keys (max_per_hour -> max_remediations_per_hour).
#   - Drops the legacy section so it doesn't keep showing up in the file.
#
# Idempotent: re-running on a config that has no [auto_remediation]
# section is a no-op.

set -euo pipefail

CONF=/etc/whp/ai-monitor.conf

if [ ! -f "$CONF" ]; then
    echo "No config at $CONF; nothing to migrate."
    exit 0
fi

if ! grep -q '^\[auto_remediation\]' "$CONF"; then
    echo "No legacy [auto_remediation] section in $CONF; nothing to migrate."
    exit 0
fi

echo "Migrating [auto_remediation] -> [remediation] in $CONF"

python3 - "$CONF" <<'PYEOF'
import configparser, sys, shutil, os

path = sys.argv[1]
backup = path + '.pre-remediation-rename'
shutil.copy2(path, backup)
print(f"Wrote backup: {backup}")

cp = configparser.ConfigParser()
cp.read(path)

if 'auto_remediation' not in cp:
    print("[auto_remediation] not present after parse; aborting clean.")
    sys.exit(0)

# Ensure [remediation] exists.
if 'remediation' not in cp:
    cp['remediation'] = {}
rem = cp['remediation']
old = cp['auto_remediation']

# Map old key -> new key (only those that changed).
RENAMES = {'max_per_hour': 'max_remediations_per_hour'}

for k, v in list(old.items()):
    new_key = RENAMES.get(k, k)
    # Skip keys the engine never used (restart_services / restart_containers /
    # edit_configs were UI-only flags).
    if k in ('restart_services', 'restart_containers', 'edit_configs'):
        continue
    # Don't overwrite a value already set in [remediation].
    if new_key not in rem:
        rem[new_key] = v
        print(f"  copied {k}={v!r} -> remediation.{new_key}")

# Drop the legacy section.
cp.remove_section('auto_remediation')

# Force conservative defaults if the operator hadn't explicitly set them.
defaults = {
    'enabled':                  'false',  # off until reviewed
    'dry_run':                  'true',   # safety on by default
    'require_high_confidence':  'true',
    'cooldown_minutes':         '60',
    'max_remediations_per_hour':'5',
    'circuit_breaker_threshold':'3',
    'backup_load_multiplier':   '4.0',
    'backup_swap_threshold':    '90',
    'allowed_services':         'httpd,php-fpm,proftpd,whp-terminal,whp-backup-upload',
    'allowed_containers':       'mysql,postgresql,haproxy-manager,memcache',
    'allowed_config_paths':     '',
}
for k, v in defaults.items():
    rem.setdefault(k, v)

with open(path, 'w') as f:
    cp.write(f)
print(f"Updated {path}")
PYEOF

echo "Migration complete."
