#!/bin/sh
# Deploys to production with ./deploy.sh when main is pushed to git.hygo.ai,
# before the push goes out: if the deploy fails, the push is stopped, so the
# repository never claims something production is not running.
#
# Enabled per clone with: git config core.hooksPath .githooks
# Skip once with: git push --no-verify   (or SKIP_DEPLOY=1 git push)
set -eu

url="$2"
[ "${SKIP_DEPLOY:-}" = 1 ] && exit 0
case "$url" in
  *git.hygo.ai/huncholane/irongit*) ;;
  *) exit 0 ;;
esac

zero=0000000000000000000000000000000000000000
deploy=0
while read -r local_ref local_sha remote_ref remote_sha; do
  [ "$remote_ref" = refs/heads/main ] || continue
  [ "$local_sha" = "$zero" ] && continue # deleting main is not a deploy
  if [ "$local_sha" != "$(git rev-parse HEAD)" ]; then
    echo "pre-push: main is $(git rev-parse --short "$local_sha") but you have $(git rev-parse --short HEAD) checked out." >&2
    echo "pre-push: check out main to deploy it, or push with --no-verify." >&2
    exit 1
  fi
  deploy=1
done
[ "$deploy" = 1 ] || exit 0

# The image is built from this folder, not the commit: refuse anything that
# is not committed (untracked files included) so prod matches main exactly.
if [ -n "$(git status --porcelain)" ]; then
  echo "pre-push: uncommitted or untracked files would be deployed:" >&2
  git status --short >&2
  echo "pre-push: commit or stash them, or push with --no-verify to skip the deploy." >&2
  exit 1
fi

echo "pre-push: deploying $(git rev-parse --short HEAD) to production before pushing main"
./deploy.sh </dev/null
