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

# Install the WordPress version-cache refresh cron + run an initial backfill.
#
# Cron runs hourly (at :17) and only refreshes rows whose wp_version_checked_at
# is NULL or older than 1 hour. Wrapped in flock+timeout per WHP convention
# (see CLAUDE.md), so a slow/stuck run never piles up.
#
# We also kick a one-shot --all run at install time so the panel shows real
# versions on the next page load instead of waiting up to an hour.

SCRIPT=/root/whp/scripts/refresh-wp-versions.sh
LOCK=/run/whp-refresh-wp-versions.lock
LOG=/var/log/whp/refresh-wp-versions.log
TIMEOUT_SECS=600   # 10 min cap; current 27-site fleet finishes in <60s.

mkdir -p /var/log/whp
chmod 0755 /var/log/whp

# The script itself comes in via update.sh's web-files / scripts rsync. If
# this installer runs BEFORE that rsync (per CLAUDE.md, update.sh runs the
# per-version scripts first), copy the script straight from the tarball so the
# cron entry has something to point at on first install.
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
TARBALL_ROOT="$(cd "$SCRIPT_DIR/../../.." && pwd)"
SRC="$TARBALL_ROOT/scripts/refresh-wp-versions.sh"
if [ -f "$SRC" ]; then
    install -m 0755 "$SRC" "$SCRIPT"
fi

if [ ! -x "$SCRIPT" ]; then
    echo "FATAL: $SCRIPT not present and not in tarball at $SRC"
    exit 1
fi

# Install crontab line idempotently. Match by command-tail so changing the
# schedule prefix doesn't dupe entries.
LINE="17 * * * * /usr/bin/flock -n ${LOCK} /usr/bin/timeout ${TIMEOUT_SECS} ${SCRIPT} --stale >>${LOG} 2>&1"

TMP=$(mktemp)
trap 'rm -f "$TMP" "$TMP.new"' EXIT

crontab -l 2>/dev/null > "$TMP" || true
if grep -F "$SCRIPT" "$TMP" >/dev/null 2>&1; then
    grep -vF "$SCRIPT" "$TMP" > "$TMP.new"
    mv "$TMP.new" "$TMP"
fi
echo "$LINE" >> "$TMP"
crontab "$TMP"
echo "Installed cron: $LINE"

# One-shot backfill so the panel's first page load after this update shows
# real versions instead of NULL/stale. Run as a background-style synchronous
# call (it's <60s on whp01 currently, well under update.sh's overall budget).
echo "Running initial wp-version backfill (--all)..."
if /usr/bin/timeout "${TIMEOUT_SECS}" "$SCRIPT" --all >>"$LOG" 2>&1; then
    echo "Initial backfill done. See $LOG for details."
else
    rc=$?
    echo "WARN: initial backfill returned rc=$rc; cron will pick up stragglers."
fi

exit 0
