#!/usr/bin/env bash
# Install this at <bare-repo>.git/hooks/post-receive on your own Git server
# (chmod +x it) and adjust DEPLOY_ROOT below. Pushing to `staging` deploys
# to the staging checkout; pushing to `main` deploys to production.
#
#   git remote add origin <you>@<git-server>:/srv/git/bookstore.git
#   git push origin staging
#
set -euo pipefail

DEPLOY_ROOT="/srv/bookstore"

while read -r oldrev newrev refname; do
  branch="${refname#refs/heads/}"

  case "$branch" in
    staging)   target="$DEPLOY_ROOT/staging";    env="staging" ;;
    main)      target="$DEPLOY_ROOT/production"; env="production" ;;
    *)         echo "post-receive: ignoring push to $branch"; continue ;;
  esac

  echo "post-receive: deploying $branch -> $env ($target)"
  mkdir -p "$target"
  git --work-tree="$target" --git-dir="$(pwd)" checkout -f "$branch"
  ( cd "$target" && ./deploy/deploy.sh "$env" )
done
