#!/usr/bin/env bash
## Staging wrapper: install the nightly container-image pull cron on an
## existing WHP server.
##
## CRITICAL: update.sh runs per-version staging scripts BEFORE rsyncing
## /root/whp/scripts/ from the tarball (per feedback_update_sh_pre_rsync_script_trap
## memory note). So at this point, /root/whp/scripts/ does NOT yet contain
## the new pull-container-images.sh or setup-image-pull-cron.sh — only the
## tarball extract does. We have to copy them into place explicitly.
##
## Tarball layout at runtime:
##   <tarball>/scripts/updates/<VERSION>/install-image-pull-cron.sh   <- this script
##   <tarball>/scripts/setup-image-pull-cron.sh
##   <tarball>/scripts/pull-container-images.sh
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# Walk up from scripts/updates/<VERSION>/ to scripts/
TARBALL_SCRIPTS="$(cd "$SCRIPT_DIR/../.." && pwd)"

NEW_PULL="$TARBALL_SCRIPTS/pull-container-images.sh"
NEW_INSTALLER="$TARBALL_SCRIPTS/setup-image-pull-cron.sh"

if [ ! -f "$NEW_PULL" ] || [ ! -f "$NEW_INSTALLER" ]; then
  echo "FATAL: tarball-shipped scripts not found at $TARBALL_SCRIPTS" >&2
  echo "  expected: pull-container-images.sh and setup-image-pull-cron.sh" >&2
  ls -la "$TARBALL_SCRIPTS" 2>&1 | head -20 >&2
  exit 1
fi

# Stage the new scripts into /root/whp/scripts/ now. After update.sh
# finishes its own rsync these will be identical anyway, but pulling them
# in here means the cron entry we write next references a real file.
mkdir -p /root/whp/scripts
install -m 0755 "$NEW_PULL"      /root/whp/scripts/pull-container-images.sh
install -m 0755 "$NEW_INSTALLER" /root/whp/scripts/setup-image-pull-cron.sh
echo "[install-image-pull-cron] staged pull-container-images.sh + setup-image-pull-cron.sh into /root/whp/scripts/"

# Now run the installer, which writes /etc/cron.d/whp-image-pull
exec /root/whp/scripts/setup-image-pull-cron.sh
