#!/usr/bin/env bash
## setup-image-pull-cron.sh — install the nightly container-image pull cron.
##
## Drops /etc/cron.d/whp-image-pull which runs scripts/pull-container-images.sh
## at 03:17 daily (off-peak, off-the-hour to avoid clock-aligned cron storms).
##
## Wrapped with flock + timeout per the WHP per-minute cron convention
## (feedback_cron_watchdog memory note); 30 min cap is plenty for ~25
## images at 1-2 min each in worst case.
##
## Idempotent — re-running is a no-op. Called from:
##   - setup.sh (fresh install / rebuild path)
##   - scripts/updates/staging/install-image-pull-cron.sh (existing-server
##     rollout via build-release + update.sh)
##
## Per project_backup_io_throttle_universal memory: host-level installers
## belong here (stable scripts/), NOT in versioned update dirs that get
## release-trimmed after 10 versions.
set -euo pipefail

CRON_FILE=/etc/cron.d/whp-image-pull
PULL_SCRIPT=/root/whp/scripts/pull-container-images.sh
LOG=/var/log/whp-image-pull.log

if [ ! -x "$PULL_SCRIPT" ]; then
  echo "[setup-image-pull-cron] ensuring $PULL_SCRIPT is executable"
  chmod +x "$PULL_SCRIPT" 2>/dev/null || true
fi

cat > "$CRON_FILE" <<EOF
# Nightly pull of all active whp.container_types base_images.
# Installed by scripts/setup-image-pull-cron.sh; do not edit by hand.
SHELL=/bin/bash
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
17 3 * * * root /usr/bin/flock -n /run/whp-image-pull.lock /usr/bin/timeout 1800 $PULL_SCRIPT >> $LOG 2>&1
EOF
chmod 0644 "$CRON_FILE"

## Ensure log dir + file exist with sane perms so first cron run doesn't
## block on a write failure.
touch "$LOG"
chmod 0644 "$LOG"

echo "[setup-image-pull-cron] installed $CRON_FILE -> 17 3 * * * $PULL_SCRIPT"
