#!/usr/bin/env bash
# setup-scheduled-site-checks.sh
#
# Installs cron entries for scheduled-site-checks.php (--daily and
# --periodic) and ensures the 'whois' tool is available.
#
# Daily   (4 AM): per-subscription log review enqueue + SSL/DNS/WHOIS checks
# Periodic (10m): per-subscription HTTP probe
#
# Idempotent — safe to run on every update. All inputs are static literals.
set -euo pipefail

SCRIPT_PATH='/root/whp/scripts/scheduled-site-checks.php'
LOG_DAILY='/var/log/whp-scheduled-checks-daily.log'
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_PERIODIC}"; do
    touch "${f}"
    chmod 0640 "${f}"
done

# Logrotate config.
cat > /etc/logrotate.d/whp-scheduled-checks <<'EOF'
/var/log/whp-scheduled-checks-daily.log
/var/log/whp-scheduled-checks-periodic.log {
    weekly
    rotate 8
    size 10M
    missingok
    notifempty
    compress
    delaycompress
}
EOF

# Build the cron lines we want present.
DAILY_LINE="0 4 * * * /usr/bin/php ${SCRIPT_PATH} --daily >> ${LOG_DAILY} 2>&1"
PERIODIC_LINE="*/10 * * * * /usr/bin/php ${SCRIPT_PATH} --periodic >> ${LOG_PERIODIC} 2>&1"

CRON_TAG_DAILY='# WHP AI Monitor - Daily per-subscription checks'
CRON_TAG_PERIODIC='# WHP AI Monitor - Periodic site-reachability probe'

# Install the daily entry idempotently (match by '--daily' arg).
if ! crontab -l 2>/dev/null | grep -F "${SCRIPT_PATH} --daily" >/dev/null; then
    (crontab -l 2>/dev/null || true; echo "${CRON_TAG_DAILY}"; echo "${DAILY_LINE}") | crontab -
    echo "Installed daily cron: ${DAILY_LINE}"
else
    echo "Daily cron already present — skipping"
fi

# Install the periodic entry idempotently (match by '--periodic' arg).
if ! crontab -l 2>/dev/null | grep -F "${SCRIPT_PATH} --periodic" >/dev/null; then
    (crontab -l 2>/dev/null || true; echo "${CRON_TAG_PERIODIC}"; echo "${PERIODIC_LINE}") | crontab -
    echo "Installed periodic cron: ${PERIODIC_LINE}"
else
    echo "Periodic cron already present — skipping"
fi

# Smoke-test the periodic mode if the script is in place. Skipped silently
# if the script hasn't been rsynced yet (update.sh runs script blocks
# before it rsyncs; cron will exercise it on the next minute).
if [[ -f "${SCRIPT_PATH}" ]]; then
    if ! /usr/bin/php "${SCRIPT_PATH}" --periodic; then
        echo "WARNING: smoke-test (--periodic) failed (non-fatal)" >&2
    fi
fi

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