#!/usr/bin/env bash
# Sando bare-repo post-receive hook.
#
# Install: copy into <bare repo>/hooks/post-receive and chmod +x.
# Reads each updated ref from stdin (old new ref) and posts the new sha to
# the daemon's /rebuild endpoint. Only the configured deploy branch is
# acted on; pushes to other refs are silently ignored.

set -euo pipefail

# Pick up SANDO_DAEMON / SANDO_BRANCH from the daemon's env file when present
# (the same file systemd's EnvironmentFile= points at). Lets the deployed hook
# reach a non-loopback listen address without changing the hook source.
if [[ -r /etc/sando/sando.env ]]; then
    set -a
    # shellcheck disable=SC1091
    source /etc/sando/sando.env
    set +a
fi

DAEMON_URL="${SANDO_DAEMON:-http://127.0.0.1:7766}"
DEPLOY_BRANCH="${SANDO_BRANCH:-main}"

while read -r oldsha newsha ref; do
    if [[ "$ref" != "refs/heads/$DEPLOY_BRANCH" ]]; then
        continue
    fi
    if [[ "$newsha" == "0000000000000000000000000000000000000000" ]]; then
        # Branch deletion; nothing to build.
        continue
    fi
    echo "sando: posting rebuild for $newsha"
    curl --silent --show-error --fail \
        -X POST "$DAEMON_URL/rebuild" \
        -H 'Content-Type: application/json' \
        -d "{\"sha\":\"$newsha\"}" \
        || echo "sando: rebuild trigger failed; check daemon"
done
