#!/usr/bin/env bash
# Zo-side supervisor for the build box, run as a process service.
# The box restores from an old snapshot on every reset, so this re-pushes the
# kit and restarts host-run.sh whenever the run has vanished, and copies the
# finished zip back to Zo the moment it exists (the box cannot be trusted to keep it).
P=$(cd "$(dirname "$0")/.." && pwd)
HOST=${HOST:?set HOST=user@build-box}; PORT=${PORT:-22}
KEY=${KEY:?set KEY=path/to/ssh/key}; export SSHPASS=${SSHPASS:?set SSHPASS}
OUT=$P/out/builds; LOG=$OUT/watch.log; mkdir -p "$OUT"
SSH="sshpass -e ssh -i $KEY -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o ServerAliveInterval=30 -o ConnectTimeout=20 -p $PORT"
r() { timeout 120 $SSH "$HOST" "$@"; }
say() { echo "$(date -u +%FT%TZ) $*" >>"$LOG"; }
start_run() {
  say "box has no run: pushing kit and starting"
  r "mkdir -p ~/.ssh && grep -qf /dev/stdin ~/.ssh/authorized_keys 2>/dev/null || cat >>~/.ssh/authorized_keys" <"$KEY.pub"
  "$P/tools/stage.sh" >>"$LOG" 2>&1
  RSYNC_RSH="$SSH" timeout 1800 rsync -az --delete --exclude .git --exclude out --exclude /build "$P/" "$HOST:/home/workspace/vanta-kit/" >>"$LOG" 2>&1 || { say "push failed"; return; }
  r "command -v tmux >/dev/null || (apt-get update -qq && apt-get install -y -qq tmux) >/dev/null 2>&1; tmux new -d -s vanta 'VANTA_DEVICE=b5q VANTA_MANIFEST=vanta-zflip5.xml /home/workspace/vanta-kit/tools/host-run.sh'" && say "run started"
}
# `touch out/builds/.restart` = start over on the box with the current kit:
# the old run's log is set aside and the watcher pushes and relaunches.
while true; do
  if [ -f "$OUT/.restart" ] && r 'tmux kill-session -t vanta 2>/dev/null; L=/home/workspace/vanta-run.log; [ ! -f $L ] || mv $L $L.$(date -u +%Y%m%d%H%M%S)'; then
    rm -f "$OUT/.restart" "$OUT/.done"; say "restart requested: old run set aside"
  fi
  st=$(r 'L=/home/workspace/vanta-run.log; [ -f $L ] || { echo NOLOG; exit; }; grep "^== " $L | tail -1; tmux has -t vanta 2>/dev/null && echo RUNNING || echo STOPPED' 2>/dev/null)
  if [ -z "$st" ]; then say "box unreachable"; sleep 120; continue; fi
  say "$(echo "$st" | tr '\n' ' ')"
  case "$st" in
    *NOLOG*) rm -f "$OUT/.failed"; start_run ;;
    *DONE*)
      z=$(r 'ls -t /home/workspace/vanta/out/target/product/*/Vanta-*.zip | head -1')
      if [ -n "$z" ] && RSYNC_RSH="$SSH" rsync -a --partial "$HOST:$z" "$OUT/" >>"$LOG" 2>&1; then
        r "sha256sum $z" >"$OUT/$(basename "$z").remote.sha256"; (cd "$OUT" && sha256sum "$(basename "$z")") >>"$LOG"
        say "PULLED $(basename "$z")"; touch "$OUT/.done"; sleep infinity
      fi ;;
    *FAILED*) [ -f "$OUT/.failed" ] || { r 'tail -80 /home/workspace/vanta-run.log' >"$OUT/failure-tail.log"; say "run FAILED, tail saved"; touch "$OUT/.failed"; } ;;
    *STOPPED*) [ -f "$OUT/.failed" ] || { say "tmux gone without DONE/FAILED"; r 'tail -40 /home/workspace/vanta-run.log' >"$OUT/failure-tail.log"; touch "$OUT/.failed"; } ;;
  esac
  sleep 120
done
