#!/usr/bin/env bash
##
## ensure-whp-crons.sh — idempotently install the canonical set of WHP host
## cron jobs.
##
## WHY THIS EXISTS: individual cron installers historically lived in versioned
## update dirs (scripts/updates/<ver>/), which build-release trims after 10
## versions. A rebuilt host therefore silently loses every cron whose installer
## aged out — whp02 came back from a rebuild missing backup-upload-worker,
## customer-container-watchdog, process-email-queue, scheduled-site-checks,
## wp-update-queue-worker, backup-cleanup, refresh-wp-versions, the traffic
## aggregator and the SSL orchestrator. This script is the single rebuild-proof
## source of truth: it lives in STABLE scripts/ and is invoked by setup.sh
## (fresh/rebuild) and a staging wrapper (existing servers).
##
## Idempotent: each entry is appended to root's crontab only if its unique key
## is absent, so re-running (or running on a fully-provisioned host) is a no-op.
## Every entry is gated on its target script existing, so a host that genuinely
## lacks a feature's script just skips that entry.
set -euo pipefail

mkdir -p /var/log/whp /run

# "key|cron line". The KEY is a script-invocation signature (script basename +
# distinguishing arg) that appears in the line REGARDLESS of whether an existing
# entry is flock-wrapped or a bare legacy form — so we never double-schedule a
# job that's already present in any shape. Lines copied verbatim from the
# canonical whp01 crontab. (Bare legacy entries are left as-is here; the flock
# wrapping of short-cadence crons is handled by wrap-per-minute-crons.sh.)
ENTRIES=(
  "wordpress-auto-update.php|0 2,8,14,20 * * * /usr/bin/php /root/whp/scripts/wordpress-auto-update.php >/dev/null 2>&1"
  "cleanup-backups.php|0 2 * * * /usr/bin/php /root/whp/scripts/cleanup-backups.php >/dev/null 2>&1"
  "backup-cleanup.php|30 2 * * * /usr/bin/flock -n /run/whp-backup-cleanup.lock /usr/bin/timeout 600 /usr/bin/php /docker/whp/web/scripts/backup-cleanup.php >> /var/log/whp-backup-cleanup.log 2>&1"
  "backup-scheduler.php|*/5 * * * * /usr/bin/flock -n /run/whp-backup-scheduler.lock /usr/bin/timeout 600 /usr/bin/php /root/whp/scripts/backup-scheduler.php >/dev/null 2>&1"
  "log_monitor_cron.sh|*/5 * * * * /usr/bin/flock -n /run/whp-log-monitor-cron.lock /usr/bin/timeout 120 /root/whp/scripts/log_monitor_cron.sh >/dev/null 2>&1"
  "refresh-system-ssl.php|0 3 * * * /usr/bin/php /root/whp/scripts/refresh-system-ssl.php >/dev/null 2>&1"
  "backup-upload-worker.php|*/2 * * * * /usr/bin/flock -n /run/whp-backup-upload.lock /usr/bin/timeout 600 /usr/bin/php /docker/whp/web/scripts/backup-upload-worker.php >/dev/null 2>&1"
  "verify-dns-challenges.php|* * * * * /usr/bin/flock -n /run/whp-verify-dns.lock /usr/bin/timeout 50 /usr/bin/php /root/whp/scripts/verify-dns-challenges.php >> /var/log/whp/dns-challenges.log 2>&1"
  "haproxy-watchdog.sh|* * * * * /usr/bin/flock -n /run/whp-haproxy-watchdog.lock /usr/bin/timeout 50 /root/whp/scripts/haproxy-watchdog.sh >> /var/log/haproxy-watchdog.log 2>&1"
  "whp-log-monitor-ai.py --mode critical|*/5 * * * * /usr/bin/flock -n /run/whp-log-monitor-ai-critical.lock /usr/bin/timeout 240 /usr/bin/python3 /root/whp/scripts/whp-log-monitor-ai.py --mode critical >> /var/log/whp-ai-monitor.log 2>&1"
  "whp-log-monitor-ai.py --mode daily|0 6 * * * /usr/bin/flock -n /run/whp-log-monitor-ai-critical.lock /usr/bin/timeout 240 /usr/bin/python3 /root/whp/scripts/whp-log-monitor-ai.py --mode daily >> /var/log/whp-ai-monitor-daily.log 2>&1"
  "process-email-queue.php|* * * * * /usr/bin/flock -n /run/whp-process-email-queue.lock /usr/bin/timeout 90 /usr/bin/php /root/whp/scripts/process-email-queue.php >> /var/log/whp-email-queue.log 2>&1"
  "process-log-review.php|* * * * * /usr/bin/flock -n /run/whp-process-log-review.lock /usr/bin/timeout 240 /usr/bin/php /root/whp/scripts/process-log-review.php >> /var/log/whp-log-review.log 2>&1"
  "ai-monitor-maintenance.php|0 3 * * * /usr/bin/php /root/whp/scripts/ai-monitor-maintenance.php >> /var/log/whp-ai-monitor-maintenance.log 2>&1"
  "scheduled-site-checks.php --daily|0 4 * * * /usr/bin/php /root/whp/scripts/scheduled-site-checks.php --daily >> /var/log/whp-scheduled-checks-daily.log 2>&1"
  "scheduled-site-checks.php --initial|*/15 * * * * /usr/bin/php /root/whp/scripts/scheduled-site-checks.php --initial >> /var/log/whp-scheduled-checks-initial.log 2>&1"
  "scheduled-weekly-summary.php|0 7 * * 1 /usr/bin/php /root/whp/scripts/scheduled-weekly-summary.php >> /var/log/whp-weekly-summary.log 2>&1"
  "whp-monitor-poll.py|* * * * * /usr/bin/flock -n /run/whp-monitor-poll.lock /usr/bin/timeout 90 /usr/bin/python3 /root/whp/scripts/whp-monitor-poll.py >> /var/log/whp-monitor-poll.log 2>&1"
  "whp-traffic-aggregator.php|0 1 * * * /usr/bin/flock -n /run/whp-traffic-aggregator.lock /usr/bin/timeout 1800 /usr/bin/php /docker/whp/web/scripts/whp-traffic-aggregator.php >> /var/log/whp-traffic-aggregator.log 2>&1"
  "whp-cpanel-import-credentials-sweep.sh|17 4 * * * /usr/bin/flock -n /run/whp-cpanel-import-sweep.lock /usr/bin/timeout 240 /root/whp/scripts/whp-cpanel-import-credentials-sweep.sh >> /var/log/whp-cpanel-import-sweep.log 2>&1"
  "refresh-wp-versions.sh|17 * * * * /usr/bin/flock -n /run/whp-refresh-wp-versions.lock /usr/bin/timeout 600 /root/whp/scripts/refresh-wp-versions.sh --stale >>/var/log/whp/refresh-wp-versions.log 2>&1"
  "wp-update-queue-worker.php|* * * * * /usr/bin/flock -n /run/whp-wp-update-queue.lock /usr/bin/timeout 300 /usr/bin/php /docker/whp/web/scripts/wp-update-queue-worker.php >/dev/null 2>&1"
  "backup-worker.php|* * * * * /usr/bin/flock -n /run/whp-backup-worker.lock /usr/bin/timeout 600 /usr/local/sbin/whp-backup-runner /usr/bin/php /docker/whp/web/scripts/backup-worker.php >/dev/null 2>&1"
  "customer-container-watchdog.sh|* * * * * /usr/bin/flock -n /run/whp-customer-watchdog.lock /usr/bin/timeout 50 /root/whp/scripts/customer-container-watchdog.sh >>/var/log/whp/customer-watchdog.log 2>&1"
  "whp-cpanel-importer-quarantine-sweep.sh|17 23 * * * /usr/bin/flock -n /run/whp-cpanel-importer-quarantine-sweep.lock /usr/bin/timeout 600 /root/whp/scripts/whp-cpanel-importer-quarantine-sweep.sh >> /var/log/whp/cpanel-importer-quarantine-sweep.log 2>&1"
  "bichon-archival-sync.sh|13 4 * * * /usr/bin/flock -n /run/whp-bichon-sync.lock /usr/bin/timeout 300 /root/whp/scripts/bichon-archival-sync.sh"
)

CUR="$(crontab -l 2>/dev/null || true)"
NEW="${CUR}"
ADDED=0
for e in "${ENTRIES[@]}"; do
  key="${e%%|*}"
  line="${e#*|}"
  # Skip if the target script is absent (e.g. an addon not installed here).
  scr="$(echo "$line" | grep -oE '/[^ ]+\.(php|py|sh)' | tail -1)"
  if [ -n "$scr" ] && [ ! -e "$scr" ]; then
    echo "  skip (script absent): $scr"
    continue
  fi
  if printf '%s\n' "$CUR" | grep -qF "$key"; then
    continue
  fi
  NEW="${NEW}"$'\n'"${line}"
  echo "  + installed: $key"
  ADDED=$((ADDED + 1))
done

if [ "$ADDED" -gt 0 ]; then
  printf '%s\n' "$NEW" | crontab -
  echo "ensure-whp-crons: added $ADDED cron entries."
else
  echo "ensure-whp-crons: all canonical crons already present."
fi

# whp-ssl-orchestrator lives in /etc/cron.d (gated by whp.settings
# ssl_orchestrator_enabled, default 0 — inert until enabled). Idempotent file
# write. Only install if the target script exists.
if [ -e /root/whp/scripts/ssl-renewal-orchestrator-cron.php ]; then
  cat > /etc/cron.d/whp-ssl-orchestrator <<'CROND'
# WHP SSL Renewal Orchestrator (gated by whp.settings.ssl_orchestrator_enabled)
SHELL=/bin/bash
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

*/30 * * * * root /usr/bin/flock -n /run/whp-ssl-orchestrator.lock /usr/bin/timeout 240 /usr/bin/php /root/whp/scripts/ssl-renewal-orchestrator-cron.php >> /var/log/whp-ssl-orchestrator.log 2>&1
CROND
  echo "ensure-whp-crons: /etc/cron.d/whp-ssl-orchestrator ensured."
fi

# sitesmith-spend-alert (cron.d, runs as root). Idempotent file write; only
# installed where the script is present.
if [ -e /root/whp/scripts/sitesmith-spend-alert.sh ]; then
  cat > /etc/cron.d/sitesmith-spend-alert <<'CROND'
# WHP SiteSmith spend alerting
17 * * * * root /root/whp/scripts/sitesmith-spend-alert.sh >/dev/null 2>&1
CROND
  echo "ensure-whp-crons: /etc/cron.d/sitesmith-spend-alert ensured."
fi
