#!/usr/bin/env bash
set -euo pipefail

###############################################################################
# setup-traffic-aggregator.sh
# Install the nightly WHP traffic aggregator cron job + log rotation.
# Idempotent — safe to re-run.
###############################################################################

LOG_FILE="/var/log/whp-traffic-aggregator.log"
LOCK_FILE="/run/whp-traffic-aggregator.lock"
SCRIPT_PATH="/docker/whp/web/scripts/whp-traffic-aggregator.php"
LOGROTATE_CONF="/etc/logrotate.d/whp-traffic-aggregator"
CRON_LINE="0 1 * * * /usr/bin/flock -n ${LOCK_FILE} /usr/bin/timeout 1800 /usr/bin/php ${SCRIPT_PATH} >> ${LOG_FILE} 2>&1"

echo "=== Setting up WHP Traffic Aggregator ==="

mkdir -p /run

# Log file
touch "${LOG_FILE}"
chmod 0644 "${LOG_FILE}"
echo "Log file: ${LOG_FILE}"

# Cron entry — append only if no existing entry references the aggregator.
if crontab -l 2>/dev/null | grep -qF "whp-traffic-aggregator"; then
    echo "Cron entry already present; leaving as-is."
else
    (crontab -l 2>/dev/null; echo "# WHP traffic analytics nightly aggregator"; echo "${CRON_LINE}") | crontab -
    echo "Cron entry installed."
fi

# Logrotate config
cat > "${LOGROTATE_CONF}" <<'LOGROTATE'
/var/log/whp-traffic-aggregator.log {
    weekly
    rotate 4
    compress
    missingok
    notifempty
}
LOGROTATE
echo "Logrotate config written: ${LOGROTATE_CONF}"

echo "=== WHP Traffic Aggregator setup complete ==="
