#!/usr/bin/env bash
# One-time migration: INI [customer_monitoring] -> MySQL ai_monitor_subscriptions,
# then drop the INI section.
# Idempotent — safe to run multiple times.
set -euo pipefail

CONF=/etc/whp/ai-monitor.conf
SETTINGS=/docker/whp/settings.json

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

# Extract sites= list (if present).
SITES_LINE="$(awk '/^\[customer_monitoring\]/{f=1;next} /^\[/{f=0} f && /^sites[[:space:]]*=/{print;exit}' "${CONF}" || true)"
ENABLED_LINE="$(awk '/^\[customer_monitoring\]/{f=1;next} /^\[/{f=0} f && /^enabled[[:space:]]*=/{print;exit}' "${CONF}" || true)"

SITES=""
if [[ -n "${SITES_LINE}" ]]; then
    SITES="$(echo "${SITES_LINE}" | cut -d'=' -f2- | tr -d '[:space:]')"
fi

ENABLED="false"
if [[ -n "${ENABLED_LINE}" ]]; then
    VAL="$(echo "${ENABLED_LINE}" | cut -d'=' -f2- | tr -d '[:space:]' | tr '[:upper:]' '[:lower:]')"
    [[ "${VAL}" == "true" || "${VAL}" == "1" || "${VAL}" == "yes" ]] && ENABLED="true"
fi

# Insert subscriptions for each domain (idempotent via INSERT IGNORE).
if [[ -n "${SITES}" ]]; then
    IFS=',' read -ra DOMAIN_ARR <<< "${SITES}"
    for DOMAIN in "${DOMAIN_ARR[@]}"; do
        [[ -z "${DOMAIN}" ]] && continue
        mysql -u root whp <<SQL
INSERT IGNORE INTO whp.ai_monitor_subscriptions (site_id, username, status, activated_at)
SELECT s.id, s.username, 'active', NOW()
FROM whp.sites s
JOIN whp.domains d ON d.id = s.primary_domain_id
WHERE d.domain_name = '${DOMAIN}'
LIMIT 1;
SQL
        echo "Migrated subscription: ${DOMAIN}"
    done
fi

# Sync global toggle into settings.json if absent.
if [[ -f "${SETTINGS}" ]]; then
    CURRENT="$(python3 -c "import json,sys; d=json.load(open('${SETTINGS}')); print(d.get('customer_monitoring',{}).get('enabled','__missing__'))" 2>/dev/null || echo __missing__)"
    if [[ "${CURRENT}" == "__missing__" ]]; then
        python3 - "${SETTINGS}" "${ENABLED}" <<'PYEOF'
import json, sys
path, enabled = sys.argv[1], sys.argv[2] == "true"
d = json.load(open(path))
d.setdefault('customer_monitoring', {})['enabled'] = enabled
json.dump(d, open(path, 'w'), indent=2)
PYEOF
        echo "Wrote customer_monitoring.enabled=${ENABLED} to settings.json"
    fi
fi

# Remove the [customer_monitoring] section from the INI.
if grep -q '^\[customer_monitoring\]' "${CONF}"; then
    awk '
        /^\[customer_monitoring\]/ {skip=1; next}
        /^\[/ {skip=0}
        !skip {print}
    ' "${CONF}" > "${CONF}.new" && mv "${CONF}.new" "${CONF}"
    chmod 0640 "${CONF}"
    echo "Removed [customer_monitoring] section from ${CONF}"
fi

echo "customer-monitoring-consolidation.sh: OK"
