#!/bin/sh
#
# Canonical bare repo hook: git://10.7.0.10/android_cast
# Install on FE (or wherever the bare repo lives):
#   cp pre-receive.android_cast.example /path/to/android_cast.git/hooks/pre-receive
#   chmod +x /path/to/android_cast.git/hooks/pre-receive
#
# Protects master and next only:
#   - reject branch deletion (git push origin :master)
#   - reject non-fast-forward / force-push
# Side branches (feature/*, fix/*, hotfix/*) are not listed — any push allowed.
#
# Optional: restrict who may update master/next (SSH user name in AUTH_USER
# or GL_USERNAME depending on git daemon setup). Uncomment ALLOWED_USERS block.
#
set -eu

PROTECTED_BRANCHES="master next"
# ALLOWED_USERS="foxx admin git"

zero="0000000000000000000000000000000000000000"

is_protected() {
  for _p in $PROTECTED_BRANCHES; do
    [ "$1" = "$_p" ] && return 0
  done
  return 1
}

# Optional user gate (uncomment ALLOWED_USERS above to enable)
check_user() {
  [ -z "${ALLOWED_USERS:-}" ] && return 0
  _u="${GL_USERNAME:-${AUTH_USER:-${USER:-}}}"
  for _a in $ALLOWED_USERS; do
    [ "$_u" = "$_a" ] && return 0
  done
  echo "hooks: user '$_u' not allowed to update protected branches" >&2
  return 1
}

while read -r oldrev newrev refname; do
  case "$refname" in
    refs/heads/*) ;;
    *) continue ;;
  esac
  branch="${refname#refs/heads/}"
  is_protected "$branch" || continue

  check_user || exit 1

  # Deletion
  if [ "$newrev" = "$zero" ]; then
    echo "hooks: refusing to delete protected branch '$branch'" >&2
    exit 1
  fi

  # New branch creation on protected name (allow only if empty repo edge case)
  if [ "$oldrev" = "$zero" ]; then
    continue
  fi

  # Non-fast-forward => force-push or history rewrite
  if ! git merge-base --is-ancestor "$oldrev" "$newrev" 2>/dev/null; then
    echo "hooks: refusing non-fast-forward push to protected branch '$branch'" >&2
    echo "hooks: use feature/* branch + merge (see docs/GIT_FLOW.md)" >&2
    exit 1
  fi
done

exit 0
