#!/usr/bin/env bash
#
# Install the SSL renewal orchestrator cron at /etc/cron.d/whp-ssl-orchestrator.
# Idempotent.
#
# The cron entry is wrapped with flock + timeout per WHP cron conventions
# (CLAUDE.md "Cron Job Conventions"; cf. feedback_cron_watchdog.md). The
# orchestrator itself is also gated by the whp.settings.ssl_orchestrator_enabled
# flag — so this cron will harmlessly log "skipped" until the flag is flipped.
#
# This script does NOT disable the haproxy-manager container's existing
# `certbot renew` cron (`0 */12 * * *`). That cutover is a separate operational
# step to be run AFTER the new orchestrator has proven itself in prod.

set -euo pipefail

CRON_FILE="/etc/cron.d/whp-ssl-orchestrator"
LOG_FILE="/var/log/whp-ssl-orchestrator.log"
LOCK_FILE="/run/whp-ssl-orchestrator.lock"
SCRIPT_PATH="/root/whp/scripts/ssl-renewal-orchestrator-cron.php"

DESIRED_CONTENT="# WHP SSL Renewal Orchestrator
# Sweeps haproxy_domains for certs needing renewal/issuance, classifies
# failures, schedules retries, queues customer emails. Gated by
# whp.settings.ssl_orchestrator_enabled (default 0 — flip to 1 to activate).
# Wrapped with flock to prevent overlap; timeout to bound runtime.
SHELL=/bin/bash
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

*/30 * * * * root /usr/bin/flock -n ${LOCK_FILE} /usr/bin/timeout 240 /usr/bin/php ${SCRIPT_PATH} >> ${LOG_FILE} 2>&1
"

# Touch the log so cron doesn't fail to write on first run, and so logrotate
# (if configured separately) sees the file exists.
touch "${LOG_FILE}"
chmod 0644 "${LOG_FILE}"

# Idempotent install: only rewrite when content actually differs.
NEEDS_INSTALL=1
if [ -f "${CRON_FILE}" ]; then
    if [ "$(cat "${CRON_FILE}")" = "${DESIRED_CONTENT}" ]; then
        NEEDS_INSTALL=0
    fi
fi

if [ "${NEEDS_INSTALL}" = "1" ]; then
    printf '%s' "${DESIRED_CONTENT}" > "${CRON_FILE}"
    chmod 0644 "${CRON_FILE}"
    echo "Installed/updated ${CRON_FILE}"
else
    echo "${CRON_FILE} already current"
fi

# Sanity check: ensure the wrapped script exists where the cron expects it.
# It's shipped via top-level scripts/ which arrives via `git pull` on /root/whp,
# not via the release tarball — so on a fresh deploy the cron may fire BEFORE
# the script is in place. The cron is harmless in that window (flock will fail
# silently because the script wasn't there to lock); just warn.
if [ ! -f "${SCRIPT_PATH}" ]; then
    echo "WARN: ${SCRIPT_PATH} not present yet — cron will become functional once /root/whp is up to date with origin/main."
fi

# crond reads /etc/cron.d/* on each minute tick — no reload needed.
echo "Cron will tick every 30 minutes; orchestrator self-skips while ssl_orchestrator_enabled=0."
