#!/usr/bin/env bash
set -euo pipefail
# whp-cpanel-import-credentials-sweep.sh
# Idempotent. Run from cron once per day.
#  - For any /var/lib/whp/cpanel-imports/*.json older than 24h with
#    mailboxes[].temp_password_encrypted OR mysql_users[].temp_password_encrypted
#    set, rewrite the file with those fields nulled and credentials_cleared_at
#    stamped.
#  - For any file older than 30d, delete entirely.

DIR=/var/lib/whp/cpanel-imports
[ -d "$DIR" ] || exit 0

NOW=$(date +%s)
ONE_DAY=$((24 * 3600))
THIRTY_DAYS=$((30 * 24 * 3600))

shopt -s nullglob
for f in "$DIR"/*.json; do
    mtime=$(stat -c %Y "$f")
    age=$((NOW - mtime))
    if [ "$age" -gt "$THIRTY_DAYS" ]; then
        echo "[sweep] DELETE $f (age ${age}s > 30d)"
        rm -f "$f"
        continue
    fi
    if [ "$age" -gt "$ONE_DAY" ]; then
        # Cheap pre-filter: look for any non-null temp_password_encrypted
        # at all. The python pass below handles both mailboxes[] and
        # mysql_users[], so the grep just needs to confirm *something*
        # is still in plaintext-encrypted form.
        if grep -q '"temp_password_encrypted": *"' "$f"; then
            tmp="$f.sweep.$$"
            python3 - "$f" "$tmp" <<'PY'
import json, sys, datetime
src, dst = sys.argv[1], sys.argv[2]
with open(src) as fh:
    s = json.load(fh)
changed = False
for m in s.get('mailboxes', []):
    if m.get('temp_password_encrypted') is not None:
        m['temp_password_encrypted'] = None
        changed = True
for u in s.get('mysql_users', []):
    if u.get('temp_password_encrypted') is not None:
        u['temp_password_encrypted'] = None
        changed = True
if changed:
    s['credentials_cleared_at'] = datetime.datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S+00:00')
    s['credentials_cleared_by'] = 'cron-sweep'
with open(dst, 'w') as fh:
    json.dump(s, fh, indent=2)
PY
            chmod 0600 "$tmp"
            mv "$tmp" "$f"
            echo "[sweep] CLEAR $f (age ${age}s > 24h)"
        fi
    fi
done
