#!/bin/bash
# Git post-receive hook for makenotwork.git on Hetzner.
#
# Handles two events:
# 1. Tag push (v*): triggers OTA build via MNW internal API (existing)
# 2. Branch push (main): triggers CI on astra via SSH (new)
#
# Install: copy to /opt/git/max/makenotwork.git/hooks/post-receive

BUILD_TOKEN="a11d2b9ff121a70e7391b36d00e812da6bba1dd91ed17d4b5e0f0dbb7f7f66cc"
# Astra's WAM (Hetzner can reach astra, but not vice versa due to Tailscale ACLs)
ASTRA_WAM_URL="http://100.106.221.39:7890"

while read oldrev newrev refname; do
    case "$refname" in
        refs/tags/v[0-9]*)
            # OTA build trigger (existing behavior)
            TAG="${refname#refs/tags/}"
            REPO_PATH="$(cd "$(dirname "$0")/.." && pwd)"
            REPO_NAME="$(basename "$REPO_PATH" .git)"
            OWNER="$(basename "$(dirname "$REPO_PATH")")"
            curl -sf -X POST \
                -H "Authorization: Bearer $BUILD_TOKEN" \
                -H "Content-Type: application/json" \
                -d "{\"repo_owner\": \"$OWNER\", \"repo_name\": \"$REPO_NAME\", \"tag\": \"$TAG\"}" \
                "http://localhost:3000/api/internal/builds/trigger" \
                >/dev/null 2>&1 &
            ;;
        refs/heads/main)
            # CI trigger: create a WAM ticket that astra's CI watcher picks up.
            # Avoids SSH ACL issues — both machines can reach WAM on localhost/tailnet.
            curl -sf -X POST "$ASTRA_WAM_URL/tickets" \
                -H "Content-Type: application/json" \
                -d "{\"title\": \"CI trigger: main pushed ($newrev)\", \"priority\": \"medium\", \"source\": \"ci-trigger\", \"source_ref\": \"$newrev\"}" \
                >/dev/null 2>&1 &
            ;;
    esac
done
