#!/usr/bin/env bash
# saturday_migration_check.sh — fires hourly on Saturday. Once phe is up + ssh
# ready, notifies the manager tmux pane and self-disables. Does NOT run the
# migration itself — that needs Cameron's live answers to 5 open questions plus
# supervision. This is a readiness signal.

set -uo pipefail

LOG="/data/cameron/agents_stuff/logs/saturday_migration.log"
CRON_MARKER="saturday_migration_check.sh"
NOW=$(date -Iseconds)
DAY=$(date +%A)
mkdir -p "$(dirname "$LOG")"

if [[ "$DAY" != "Saturday" ]]; then
  echo "$NOW  not Saturday ($DAY), skipping" >> "$LOG"
  exit 0
fi

if ! timeout 3 ping -c 1 -W 2 100.74.71.38 >/dev/null 2>&1; then
  echo "$NOW  phe still down — will retry next hour" >> "$LOG"
  exit 0
fi

if ! timeout 8 ssh -o BatchMode=yes -o ConnectTimeout=6 cameronsmith@100.74.71.38 'echo ready' >/dev/null 2>&1; then
  echo "$NOW  ping OK but ssh not ready — will retry next hour" >> "$LOG"
  exit 0
fi

UPTIME=$(timeout 6 ssh -o BatchMode=yes cameronsmith@100.74.71.38 'uptime | head -c 100' 2>/dev/null || echo unknown)
echo "$NOW  phe up ($UPTIME); notifying manager + self-disabling" >> "$LOG"

{
  timeout 5 tmux send-keys -t agents:manager C-u
  sleep 1
  timeout 5 tmux send-keys -t agents:manager -l "[saturday_migration] Saturday-migration readiness signal fired at $NOW. Phe is confirmed up (uptime: $UPTIME) and ssh-able. Cameron scheduled the yam-code migration for today. Before I start any rsync, I need Cameron's answers to the 5 open questions in migration/YAM_CODE_MIGRATION_PLAN.md: (1) one big repo or split, (2) vault + manager-memory GitHub repo names, (3) OK to add VPS's pubkey to phe/puget/yukon authorized_keys so compute hosts can sshfs FROM VPS, (4) nightly backup cadence, (5) any existing GitHub repos we'd merge into vs. new ones. Also — did yams's manifest come in? Its outbox is the file-list source of truth for Phase B. Ready to walk through when you and Cameron are."
  sleep 1
  timeout 5 tmux send-keys -t agents:manager Enter
  sleep 1
  timeout 5 tmux send-keys -t agents:manager Enter
} 2>/dev/null || echo "$NOW  (tmux notify failed silently)" >> "$LOG"

(crontab -l 2>/dev/null | grep -v "$CRON_MARKER") | crontab -
echo "$NOW  cron self-disabled" >> "$LOG"
