#!/usr/bin/env bash
# Remove apps/105 Gitea webhooks from the oikos repo.
# apps/105 is stopped; its deploy webhook (ids 10, 11) should be removed
# so pushes no longer trigger deploys to the old Python stack.
#
# Usage:
#   GITEA_TOKEN="<your-token>" ./scripts/cleanup-apps105-webhooks.sh
#
# Get a token: git.hubris.network → Settings → Applications → Generate Token
# Scopes needed: write:repository

set -euo pipefail

GITEA_URL="${GITEA_URL:-https://git.hubris.network}"
REPO="${REPO:-dtoro/oikos}"
TOKEN="${GITEA_TOKEN:-}"

if [ -z "$TOKEN" ]; then
    echo "ERROR: GITEA_TOKEN not set"
    echo "Usage: GITEA_TOKEN='...' $0"
    exit 1
fi

echo "=== Listing webhooks for $REPO ==="
HOOKS=$(curl -s -H "Authorization: token $TOKEN" \
    "$GITEA_URL/api/v1/repos/$REPO/hooks")

echo "$HOOKS" | jq -r '.[] | "  id=\(.id) url=\(.config.url) active=\(.active)"'

# Find hooks pointing to apps/105
APPS105_HOOKS=$(echo "$HOOKS" | jq -r '.[] | select(.config.url | test("apps105|192.168.8.105")) | .id')

if [ -z "$APPS105_HOOKS" ]; then
    echo ""
    echo "No apps/105 webhooks found. Nothing to do."
    exit 0
fi

echo ""
echo "=== Found apps/105 webhooks ==="
for id in $APPS105_HOOKS; do
    URL=$(echo "$HOOKS" | jq -r ".[] | select(.id == $id) | .config.url")
    echo "  Hook $id → $URL"
done

echo ""
read -p "Delete these webhooks? [y/N] " CONFIRM

if [ "$CONFIRM" != "y" ] && [ "$CONFIRM" != "Y" ]; then
    echo "Aborted."
    exit 0
fi

for id in $APPS105_HOOKS; do
    echo "Deleting hook $id..."
    RESP=$(curl -s -w "%{http_code}" -o /dev/null \
        -X DELETE \
        -H "Authorization: token $TOKEN" \
        "$GITEA_URL/api/v1/repos/$REPO/hooks/$id")
    if [ "$RESP" = "204" ]; then
        echo "  ✓ Hook $id deleted"
    else
        echo "  ✗ Hook $id: HTTP $RESP"
    fi
done

echo ""
echo "=== Done ==="
