#!/usr/bin/env bash
# setup-scheduled-site-checks-v2.sh
#
# Re-installs the cron entries for scheduled-site-checks.php after the
# scheduler was reorganized:
#   --daily    runs HTTP + SSL + DNS + WHOIS once per day at 4 AM
#   --initial  backfills new subscriptions every 15 minutes
#
# The previous --periodic entry is removed (per-minute backend monitoring
# now handles site-down detection via whp-monitor-poll.py).
#
# Idempotent — safe to run on every update.
set -euo pipefail

SCRIPT_PATH='/root/whp/scripts/scheduled-site-checks.php'
LOG_DAILY='/var/log/whp-scheduled-checks-daily.log'
LOG_INITIAL='/var/log/whp-scheduled-checks-initial.log'
OLD_LOG_PERIODIC='/var/log/whp-scheduled-checks-periodic.log'

# Ensure 'whois' is installed (used by --daily for domain expiry).
if ! command -v whois >/dev/null 2>&1; then
    echo "Installing whois..."
    if command -v dnf >/dev/null 2>&1; then
        dnf install -y whois
    elif command -v apt-get >/dev/null 2>&1; then
        apt-get update -qq && apt-get install -y whois
    else
        echo "WARNING: neither dnf nor apt-get found; install 'whois' manually for domain expiry checks." >&2
    fi
fi

# Ensure log files exist with safe perms.
for f in "${LOG_DAILY}" "${LOG_INITIAL}"; do
    touch "${f}"
    chmod 0640 "${f}"
done

# Logrotate config (covers all current + legacy files).
cat > /etc/logrotate.d/whp-scheduled-checks <<'EOF'
/var/log/whp-scheduled-checks-daily.log
/var/log/whp-scheduled-checks-initial.log
/var/log/whp-scheduled-checks-periodic.log {
    weekly
    rotate 8
    size 10M
    missingok
    notifempty
    compress
    delaycompress
}
EOF

# Build current crontab, scrubbing any stale entries we control.
CURRENT_CRON="$(crontab -l 2>/dev/null || true)"
SCRUBBED_CRON="$(printf '%s\n' "${CURRENT_CRON}" | grep -v -F "${SCRIPT_PATH}" | grep -v 'WHP AI Monitor - .*per-subscription checks' | grep -v 'WHP AI Monitor - .*site-reachability probe' | grep -v 'WHP AI Monitor - .*backfill' || true)"

DAILY_LINE="0 4 * * * /usr/bin/php ${SCRIPT_PATH} --daily >> ${LOG_DAILY} 2>&1"
INITIAL_LINE="*/15 * * * * /usr/bin/php ${SCRIPT_PATH} --initial >> ${LOG_INITIAL} 2>&1"

{
    printf '%s\n' "${SCRUBBED_CRON}"
    echo '# WHP AI Monitor - Daily per-subscription checks'
    echo "${DAILY_LINE}"
    echo '# WHP AI Monitor - Backfill checks for new subscriptions'
    echo "${INITIAL_LINE}"
} | crontab -

echo "Installed cron:"
echo "  ${DAILY_LINE}"
echo "  ${INITIAL_LINE}"

# Retire the old periodic log file (kept around so logrotate can compress
# its tail, but stop adding to it).
if [[ -f "${OLD_LOG_PERIODIC}" ]]; then
    : >> "${OLD_LOG_PERIODIC}"  # touch
fi

# Smoke-test the --initial mode (no-op if nothing to backfill).
if [[ -f "${SCRIPT_PATH}" ]]; then
    if ! /usr/bin/php "${SCRIPT_PATH}" --initial; then
        echo "WARNING: smoke-test (--initial) failed (non-fatal)" >&2
    fi
fi

echo "setup-scheduled-site-checks-v2.sh: OK"
