#!/usr/bin/env bash
#
# setup-weekly-summary-cron.sh
#
# Installs the cron entry for /root/whp/scripts/scheduled-weekly-summary.php.
# Runs Mondays at 07:00 (server timezone). Idempotent — safe to re-run on
# every update; it greps the existing crontab and only appends when the
# entry is absent.
#
set -euo pipefail

SCRIPT_PATH='/root/whp/scripts/scheduled-weekly-summary.php'
LOG_FILE='/var/log/whp-weekly-summary.log'

CRON_TAG='# WHP AI Monitor - Weekly per-subscription summary email'
CRON_LINE="0 7 * * 1 /usr/bin/php ${SCRIPT_PATH} >> ${LOG_FILE} 2>&1"

# Ensure log file exists with safe perms.
touch "${LOG_FILE}"
chmod 0640 "${LOG_FILE}"

# Logrotate config (matches the pattern used by the daily checks).
cat > /etc/logrotate.d/whp-weekly-summary <<'EOF'
/var/log/whp-weekly-summary.log {
    weekly
    rotate 8
    size 10M
    missingok
    notifempty
    compress
    delaycompress
}
EOF

# Idempotent install: match by full script path so we don't collide with
# the daily/periodic entries that share the same scripts directory.
if ! crontab -l 2>/dev/null | grep -F "${SCRIPT_PATH}" >/dev/null; then
    (crontab -l 2>/dev/null || true; echo "${CRON_TAG}"; echo "${CRON_LINE}") | crontab -
    echo "Installed weekly-summary cron: ${CRON_LINE}"
else
    echo "Weekly-summary cron already present — skipping install"
fi

echo "setup-weekly-summary-cron.sh: OK"
