#!/usr/bin/env bash
##
## wrap-monitor-poll-cron.sh — ensure the per-minute whp-monitor-poll.py cron is
## flock + timeout wrapped.
##
## whp-monitor-poll.py runs every minute and now performs docker operations
## (per-site PHP/health probes and, on a confirmed failure, container restarts).
## Without flock+timeout a slow/hung cycle could pile up minute-over-minute. It
## was never added to wrap-per-minute-crons.sh (2026.04.140); this brings it in
## line with every other short-cadence WHP cron. 240s matches the other
## docker/AI-heavy workers.
##
## Idempotent: if the cron line is already flock-wrapped, it is left untouched.
set -euo pipefail

SCRIPT_PATH="/root/whp/scripts/whp-monitor-poll.py"
TIMEOUT=240
LOCK="/run/whp-monitor-poll.lock"

CURRENT="$(crontab -l 2>/dev/null || true)"

if ! echo "${CURRENT}" | grep -qF "${SCRIPT_PATH}"; then
  echo "[wrap-monitor-poll] no crontab entry for ${SCRIPT_PATH} — nothing to do."
  exit 0
fi

if echo "${CURRENT}" | grep -F "${SCRIPT_PATH}" | grep -q "flock"; then
  echo "[wrap-monitor-poll] already wrapped — no change."
  exit 0
fi

# Wrap only the command portion (fields 6+), preserving the schedule (fields 1-5)
# and any redirection. Match the exact line so we don't disturb other entries.
NEW="$(echo "${CURRENT}" | awk -v sp="${SCRIPT_PATH}" -v to="${TIMEOUT}" -v lk="${LOCK}" '
  index($0, sp) && $0 !~ /flock/ && $0 !~ /^[[:space:]]*#/ {
    sched = $1" "$2" "$3" "$4" "$5
    cmd = ""
    for (i = 6; i <= NF; i++) cmd = cmd (i > 6 ? " " : "") $i
    print sched " /usr/bin/flock -n " lk " /usr/bin/timeout " to " " cmd
    next
  }
  { print }
')"

echo "${NEW}" | crontab -
echo "[wrap-monitor-poll] wrapped ${SCRIPT_PATH} (timeout ${TIMEOUT}s, lock ${LOCK})."
