#!/usr/bin/env bash
# Deploys are invoked as `bash <caller-checkout>/packaging/deploy-local.sh` against the one
# shared clone, so a caller parked on an old commit runs deploy logic older than the release
# it is publishing. Once the clone is at origin/main the script must hand over to the clone's
# own copy, or every future deploy step is optional depending on who typed the command.
set -uo pipefail

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
SCRIPT="$ROOT/packaging/deploy-local.sh"
fails=0
check() { if [ "$1" = 0 ]; then printf 'ok - %s\n' "$2"; else printf 'FAIL - %s\n' "$2"; fails=$((fails + 1)); fi; }

bash -n "$SCRIPT"
check $? "deploy-local.sh parses"

checkout_line=$(grep -n 'git checkout --quiet --detach "$OVERDECK_DEPLOY_TARGET_SHA"' "$SCRIPT" | tail -1 | cut -d: -f1)
[[ -n "$checkout_line" ]]
check $? "found the checkout that publishes the selected release"

reexec_line=$(grep -n 'exec "$BASH" "$DEPLOY/packaging/deploy-local.sh"' "$SCRIPT" | tail -1 | cut -d: -f1)
[[ -n "$reexec_line" && "$reexec_line" -gt "$checkout_line" ]]
check $? "a stale running script hands over after checkout"

sed -n "1,${reexec_line}p" "$SCRIPT" | grep -q 'OVERDECK_DEPLOY_CHECKOUT_REEXEC:-'
check $? "the post-checkout handover cannot recurse"

digest_line=$(grep -n 'RUNNING_DEPLOY_SCRIPT_DIGEST=' "$SCRIPT" | head -1 | cut -d: -f1)
if [[ -n "$digest_line" && "$digest_line" -lt "$checkout_line" ]] \
  && sed -n "${checkout_line},${reexec_line}p" "$SCRIPT" | grep -q 'RUNNING_DEPLOY_SCRIPT_DIGEST.*checked_out_script_digest'; then
  rc=0
else
  rc=1
fi
check "$rc" "handover compares process-start bytes, not the checkout-mutated script path"

# The handover must be reached before anything is installed from the caller's copy.
first_install=$(grep -n '^bash .*modules/gptbridge/install.sh' "$SCRIPT" | head -1 | cut -d: -f1)
[ -n "$first_install" ] && [ "$reexec_line" -lt "$first_install" ]
check $? "the handover happens before the first install step"

# The fleet's runtime target is read from the clone, never written to a side file that a
# publish path can forget: three of them did.
! grep -rq --exclude-dir=tests 'claude-runtime-release.json' "$ROOT/packaging" "$ROOT/modules/workstation/claude"
check $? "no deploy path owns a separate runtime release record"

[ "$fails" -eq 0 ] || { printf '%s check(s) failed\n' "$fails" >&2; exit 1; }
printf 'deploy-runs-landed-script: all checks passed\n'
