#!/usr/bin/env bash
# Hardened deploy orchestrator for atproto-bridge. Run from the publisher box (tabertron)
# AFTER `git push pear master` so CI has published the new version.
#
# Replaces the ad-hoc `ssh <host> 'pgh app stop; install; start'` one-liners that stranded
# prod on 2026-07-03. Copies the hardened swap script to the host and runs it there:
# serialized, bounded install, always-restart, health-verified, rollback-on-failure.
#
# Usage:
# scripts/deploy.sh <host> [version] # deploy; if version given, wait for CI publish first
# scripts/deploy.sh <host> --check # report remote tree/status/health, change nothing
set -uo pipefail
HOST="${1:?usage: deploy.sh <host> [version|--check]}"
ARG="${2:-}"
APP=atproto-bridge
PORT=3399
HERE="$(cd "$(dirname "$0")" && pwd)"
push_remote() { scp -q "$HERE/remote-deploy.sh" "$HOST:/tmp/remote-deploy-$APP.sh"; }
if [ "$ARG" = "--check" ]; then
push_remote
ssh -o ConnectTimeout=10 "$HOST" "bash /tmp/remote-deploy-$APP.sh $APP $PORT --check"
exit $?
fi
# Optionally wait for CI to publish <version> into the local pgh registry before swapping.
if [ -n "$ARG" ]; then
echo "[deploy] waiting for $APP@$ARG in the pgh registry…"
for _ in $(seq 1 60); do
grep -q "\"$ARG\"" "$HOME/.config/pgh/published-index.json" 2>/dev/null && { echo "[deploy] $ARG published"; break; }
sleep 5
done
fi
echo "[deploy] copying hardened swap script to $HOST"
push_remote
echo "[deploy] running hardened swap on $HOST (serialized, verified, rollback-on-failure)"
ssh -o ConnectTimeout=10 "$HOST" "bash /tmp/remote-deploy-$APP.sh $APP $PORT"