#!/bin/sh
# Refuses a direct push to main: changes reach main through a pull request that was approved on
# GitHub. Enabled per clone with:  git config core.hooksPath .githooks
#
# For a push the owner has approved (e.g. a release), allow it once:
#   ALLOW_MAIN_PUSH=1 git push origin main
# GitHub's own branch protection (see README, "Contributing") enforces the same rule server-side.

protected="refs/heads/main"

while read -r local_ref local_sha remote_ref remote_sha; do
  if [ "$remote_ref" = "$protected" ]; then
    if [ "${ALLOW_MAIN_PUSH:-}" = "1" ]; then
      echo "pre-push: pushing to main (ALLOW_MAIN_PUSH=1, approved by the owner)." >&2
      continue
    fi
    echo "pre-push: direct pushes to main are blocked." >&2
    echo "  Push a branch and open a pull request:  git push -u origin <branch>" >&2
    echo "  Approved by the owner?  ALLOW_MAIN_PUSH=1 git push origin main" >&2
    exit 1
  fi
done
exit 0
