#!/bin/bash
# DEPRECATED: Use the statis-webhook module instead
# 
# To trigger webhook notifications, use the Yii console command:
#   php yii statis-webhook/webhook/trigger
#
# Or programmatically via StatisWebhookClient component.
# See: https://dev.azure.com/PortalPeopleUK/NGauge_Modules/_git/statis-webhook
#
# This script is kept for backwards compatibility but will be removed in v2.0.0

echo "WARNING: trigger-webhook.sh is deprecated"
echo "Please use: php yii statis-webhook/webhook/trigger"
echo ""

# Configuration
WEBHOOK_URL="https://scupuhfsfu.portalpeople.co.uk/webhook/devops"
TOKEN="6ed3af48ce03a4bcb16b11e5b70fc85301507342195b3a41eeb53abbfe0f1f23"

# Get git metadata
REPO_URL=$(git remote get-url origin)
COMMIT_ID=$(git rev-parse HEAD)
COMMIT_MESSAGE=$(git log -1 --pretty=%B)
COMMIT_AUTHOR=$(git log -1 --pretty=%an)
COMMIT_EMAIL=$(git log -1 --pretty=%ae)
COMMIT_DATE=$(git log -1 --pretty=%aI)

# Construct JSON payload (Azure DevOps git.push webhook format)
PAYLOAD=$(cat <<EOF
{
  "subscriptionId": "manual-trigger",
  "notificationId": 1,
  "id": "manual-trigger",
  "eventType": "git.push",
  "publisherId": "tfs",
  "message": {
    "text": "Manual webhook trigger for Statis package update"
  },
  "resource": {
    "commits": [
      {
        "commitId": "$COMMIT_ID",
        "author": {
          "name": "$COMMIT_AUTHOR",
          "email": "$COMMIT_EMAIL",
          "date": "$COMMIT_DATE"
        },
        "committer": {
          "name": "$COMMIT_AUTHOR",
          "email": "$COMMIT_EMAIL",
          "date": "$COMMIT_DATE"
        },
        "comment": "$COMMIT_MESSAGE"
      }
    ],
    "repository": {
      "id": "ngauge-caterpoint",
      "name": "ngauge-caterpoint",
      "url": "$REPO_URL",
      "remoteUrl": "$REPO_URL"
    },
    "pushedBy": {
      "displayName": "$COMMIT_AUTHOR",
      "uniqueName": "$COMMIT_EMAIL"
    }
  },
  "createdDate": "$(date -Iseconds)"
}
EOF
)

# Send webhook
echo "Triggering Statis webhook for commit $COMMIT_ID..."
RESPONSE=$(curl -s -w "\nHTTP_STATUS:%{http_code}" \
  -X POST \
  -H "X-DEVOPS-TOKEN: $TOKEN" \
  -H "Content-Type: application/json; charset=utf-8" \
  -d "$PAYLOAD" \
  "$WEBHOOK_URL")

# Parse response
HTTP_BODY=$(echo "$RESPONSE" | sed -e 's/HTTP_STATUS:.*//g')
HTTP_STATUS=$(echo "$RESPONSE" | tr -d '\n' | sed -e 's/.*HTTP_STATUS://')

# Display result
if [ "$HTTP_STATUS" -eq 200 ]; then
  echo "✓ Webhook triggered successfully (HTTP $HTTP_STATUS)"
  echo "  Response: $HTTP_BODY"
else
  echo "✗ Webhook failed (HTTP $HTTP_STATUS)"
  echo "  Response: $HTTP_BODY"
  exit 1
fi
