#!/usr/bin/env bash
# Installs whp-monitor-poll.py as a minute-cadence cron job.
# Idempotent — safe to run multiple times.
set -euo pipefail

SCRIPT_PATH='/root/whp/scripts/whp-monitor-poll.py'
LOG_PATH='/var/log/whp-monitor-poll.log'
CRON_TAG='# WHP AI Monitor - Minute-cadence poll'

# The script may not exist yet on first install — update.sh rsyncs scripts
# AFTER running update scripts. Install the cron entry anyway; the next
# cron firing (within 1 minute) runs after the rsync is complete.
if [[ -f "${SCRIPT_PATH}" ]]; then
    chmod 0755 "${SCRIPT_PATH}"
else
    echo "Note: ${SCRIPT_PATH} not yet in place — cron will pick it up after rsync."
fi

# Ensure log file exists and has safe perms. Installer runs as root, so
# touch creates it root-owned — no explicit chown needed (the update.sh
# safety validator also rejects chown patterns).
touch "${LOG_PATH}"
chmod 0640 "${LOG_PATH}"

# Logrotate config (10 files x 10MB).
cat > /etc/logrotate.d/whp-monitor-poll <<'EOF'
/var/log/whp-monitor-poll.log {
    weekly
    rotate 10
    size 10M
    missingok
    notifempty
    compress
    delaycompress
}
EOF

# Install cron entry idempotently.
CRON_LINE="* * * * * /usr/bin/python3 ${SCRIPT_PATH} >> ${LOG_PATH} 2>&1"
if ! crontab -l 2>/dev/null | grep -qF "${SCRIPT_PATH}"; then
    (crontab -l 2>/dev/null || true; echo "${CRON_TAG}"; echo "${CRON_LINE}") | crontab -
    echo "Installed cron entry: ${CRON_LINE}"
else
    echo "Cron entry already present — skipping"
fi

# Smoke-test one run if script is present. Skip if update.sh hasn't
# rsynced scripts yet — cron will exercise it within 1 minute.
if [[ -f "${SCRIPT_PATH}" ]]; then
    if ! python3 "${SCRIPT_PATH}"; then
        echo "WARNING: smoke-test run of ${SCRIPT_PATH} failed (non-fatal)" >&2
    fi
fi

echo "setup-whp-monitor-poll.sh: OK"
