#!/usr/bin/env bash
set -euo pipefail
# reinstall-cpanel-import-credentials-sweep.sh
#
# The 24h credential sweeper was originally installed in 2026.05.49 from
# scripts/updates/2026.05.49/whp-cpanel-import-credentials-sweep.sh, copying
# the body to /root/whp/scripts/whp-cpanel-import-credentials-sweep.sh.
#
# This release extends the sweeper to also zero mysql_users[].temp_password_encrypted
# alongside mailboxes[]. The on-disk script body in the prior version's dir
# was updated, but the deployed copy is from when the install ran on each
# server. Re-copy it so servers that already ran update.sh past 2026.05.49
# pick up the new logic.
#
# Cron entry installed by the prior version is left alone — same path, same
# wrapping, same cadence, only the script body changes.

HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# When build-release.sh runs, this script will be moved into its versioned
# dir at scripts/updates/<version>/ and the sweeper source is shipped from
# scripts/updates/2026.05.49/whp-cpanel-import-credentials-sweep.sh. update.sh
# extracts the whole release tarball before running per-version scripts, so
# the prior version's path is on disk.
SRC="$HERE/../2026.05.49/whp-cpanel-import-credentials-sweep.sh"
DEST=/root/whp/scripts/whp-cpanel-import-credentials-sweep.sh

if [ ! -f "$SRC" ]; then
    echo "sweeper source not found at $SRC — skipping reinstall"
    exit 0
fi

mkdir -p /root/whp/scripts
cp "$SRC" "$DEST"
chmod 0750 "$DEST"
echo "Reinstalled credential sweeper: $DEST"

# Confirm cron is in place — if a fresh server has never run 2026.05.49, the
# cron entry won't exist. Install it idempotently (same line shape as the
# original installer).
CRON_LINE="17 4 * * * /usr/bin/flock -n /run/whp-cpanel-import-sweep.lock /usr/bin/timeout 240 $DEST >> /var/log/whp-cpanel-import-sweep.log 2>&1"
CRONTAB="$(crontab -l 2>/dev/null || true)"
if echo "$CRONTAB" | grep -qF "$DEST"; then
    echo "Cron already present: $DEST"
else
    (echo "$CRONTAB"; echo "$CRON_LINE") | crontab -
    echo "Cron installed: $CRON_LINE"
fi
