#!/bin/bash
# Bootstrap hook for the bare repo of a production install. Install it once as
# <bare repo>/hooks/post-receive (mode 0755). It never needs to change: the real
# deploy is deploy/hook.sh in the pushed commit, so a change to the deploy rides
# the same push as the code it deploys.
#
# Runs as the app user with cwd = the bare repo and GIT_DIR pointing at it.
# AUTOCRAFT_BRANCH (default main) is the branch that deploys.
set -euo pipefail

branch="${AUTOCRAFT_BRANCH:-main}"
deploy=0
while read -r _old _new ref; do
	if [ "$ref" = "refs/heads/$branch" ]; then deploy=1; fi
done
if [ "$deploy" -eq 0 ]; then
	echo "-- no $branch update; nothing to deploy --"
	exit 0
fi

if ! git cat-file -e "refs/heads/$branch:deploy/hook.sh" 2>/dev/null; then
	echo "!! the pushed commit has no deploy/hook.sh; nothing was deployed" >&2
	exit 1
fi

# Run the hook from a copy: the checkout it updates may replace deploy/hook.sh mid-run.
hook="$(mktemp "$(cd "$GIT_DIR/.." && pwd)/.post-receive-hook.XXXXXX")"
trap 'rm -f "$hook"' EXIT
git cat-file blob "refs/heads/$branch:deploy/hook.sh" >"$hook"
AUTOCRAFT_BRANCH="$branch" bash "$hook"
