#!/usr/bin/env bash
set -euo pipefail

# fix-webhook.sh — Fix Woodpecker webhook to use internal cluster URL
# Run this after activating the repo in the Woodpecker UI

GITEA_AUTH="Authorization: Basic $(echo -n 'admin:St0nks0racl3!' | base64)"
GITEA_API="http://10.1.1.12:30300/api/v1"

HOOK_ID=$(curl -s -H "$GITEA_AUTH" "$GITEA_API/repos/admin/stonks-oracle/hooks" | python3 -c '
import sys, json
hooks = json.loads(sys.stdin.read())
for h in hooks:
    if "woodpecker" in h["config"]["url"] or "hook" in h["config"]["url"]:
        print(h["id"])
        break
' 2>/dev/null || echo "")

if [ -z "$HOOK_ID" ]; then
  echo "No Woodpecker webhook found. Activate the repo in Woodpecker first."
  exit 1
fi

TOKEN=$(curl -s -H "$GITEA_AUTH" "$GITEA_API/repos/admin/stonks-oracle/hooks/$HOOK_ID" | \
  python3 -c 'import sys,json; print(json.loads(sys.stdin.read())["config"]["url"].split("access_token=")[1])')

curl -s -X PATCH -H "$GITEA_AUTH" -H "Content-Type: application/json" \
  "$GITEA_API/repos/admin/stonks-oracle/hooks/$HOOK_ID" \
  -d "{\"config\":{\"url\":\"http://woodpecker-server.woodpecker.svc.cluster.local:80/api/hook?access_token=${TOKEN}\",\"content_type\":\"json\"},\"active\":true}" > /dev/null

echo "✓ Webhook fixed to internal URL"
