#!/usr/bin/env bash
# Sando bare-repo post-receive hook.
#
# Installed at <bare repo>/hooks/post-receive by bootstrap-sandod-host.sh.
# 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

# Source the operator's sando.env so $SANDO_DAEMON resolves to the tailnet
# listener, not the 127.0.0.1 default. Hooks run in the ssh push context with
# no environment, so this source step is load-bearing. Tolerate missing file
# so the hook still works in a dev clone.
if [[ -f /etc/sando/sando.env ]]; then
    # shellcheck disable=SC1091
    source /etc/sando/sando.env
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
