#!/usr/bin/env bash
#
# Install the Coraza audit-log rollup cron at /etc/cron.d/whp-coraza-audit-rollup.
# Idempotent.
#
# Parses /var/log/coraza/audit.log every 5 min and rebuilds the
# coraza_rule_hits cache in security.db. Wrapped with flock + timeout per
# WHP cron conventions (CLAUDE.md "Cron Job Conventions";
# cf. feedback_cron_watchdog.md). Skips no-op on hosts where audit.log
# doesn't yet exist (the rollup script's own early-exit).

set -euo pipefail

CRON_FILE="/etc/cron.d/whp-coraza-audit-rollup"
LOG_FILE="/var/log/whp-coraza-rollup.log"
LOCK_FILE="/run/whp-coraza-audit-rollup.lock"
SCRIPT_PATH="/root/whp/scripts/coraza-audit-rollup.php"

DESIRED_CONTENT="# WHP Coraza Audit-Log Rollup
# Parses /var/log/coraza/audit.log into the coraza_rule_hits cache table
# (24h + 7d windows). The WHP rule-manager UI reads this cache; never the raw log.
# 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

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

touch "${LOG_FILE}"
chmod 0644 "${LOG_FILE}"

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

echo "Cron will tick every 5 minutes; rollup self-skips when audit.log is absent."
