#!/usr/bin/env bash
# The whole unattended run on the build host:
#   update kit -> bootstrap -> stage -> sync -> apply -> build
# Each step is checked explicitly: wrapping the steps in `{ } || ...` switches
# set -e off, which is how a half-synced tree once went on to apply and build.
#
# Usage (from a clone of https://vanta.failure.fail/git/vanta/vanta):
#   VANTA_DEVICE=b5q tools/host-run.sh          # Galaxy Z Flip5 (default)
#   VANTA_DEVICE=gsi_arm64 tools/host-run.sh    # GSI
# Optional: SRC (source tree, default /home/workspace/vanta), LOG, VANTA_PULL=0.
KIT=${KIT:-$(cd "$(dirname "$0")/.." && pwd)}
SRC=${SRC:-/home/workspace/vanta}
[ -f "$KIT/device.env" ] && . "$KIT/device.env"
VANTA_DEVICE=${VANTA_DEVICE:-b5q}; export VANTA_DEVICE
LOG=${LOG:-/home/workspace/vanta-run.log}
mkdir -p "$(dirname "$LOG")"
exec >>"$LOG" 2>&1
# Harmless belt-and-braces: Go raises its own soft limit. Real EMFILE on the
# box is sentry host-handle exhaustion, which fdprobe.py catches.
ulimit -n "$(ulimit -Hn)" 2>/dev/null || ulimit -n 1048576
echo "== fd limit $(ulimit -n)"
step() { local n=$1; shift; echo "== $(date -u) $n"; "$@"; local rc=$?; [ $rc -eq 0 ] || { echo "== $(date -u) FAILED at $n rc=$rc"; exit 1; }; }
if [ "${VANTA_PULL:-1}" = 1 ] && [ -d "$KIT/.git" ]; then
  step pull    git -C "$KIT" pull --ff-only
fi
step profile   bash -c ". '$KIT/tools/lib/profile.sh' && vanta_profile '$KIT' && echo \"device \$VANTA_DEVICE -> \$VANTA_PRODUCT (m \$VANTA_TARGET)\""
step start     "$KIT/tools/host-bootstrap.sh"
step stage     "$KIT/tools/stage.sh"
step fdprobe   python3 "$KIT/tools/fdprobe.py" "$SRC"
"$KIT/tools/preflight.sh" "$SRC" || true
step sync      "$KIT/tools/sync.sh" "$SRC"
step apply     "$KIT/tools/apply.sh" "$SRC"
step fdprobe2  python3 "$KIT/tools/fdprobe.py" "$SRC"
step build     "$KIT/tools/build.sh" "$SRC"
echo "== $(date -u) DONE"
