#!/usr/bin/env bash
set -euo pipefail
# install-cpanel-import-credentials-sweep.sh
# Runs once per release as part of update.sh.

# update.sh runs per-version scripts BEFORE rsyncing /root/whp/, so look up
# the sweeper from a path relative to this script's own location (= the
# extracted release tarball).
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SRC="$HERE/whp-cpanel-import-credentials-sweep.sh"
DEST=/root/whp/scripts/whp-cpanel-import-credentials-sweep.sh

mkdir -p /root/whp/scripts /var/lib/whp/cpanel-imports
chmod 0700 /var/lib/whp/cpanel-imports

cp "$SRC" "$DEST"
chmod 0750 "$DEST"

# Wrap with flock + timeout per project cron conventions.
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 installed: $DEST"
else
    (echo "$CRONTAB"; echo "$CRON_LINE") | crontab -
    echo "Cron installed: $CRON_LINE"
fi
