#!/bin/bash

# This script sends a notification to Feishu
# Usage: ./send-notification.sh <status> <commit_msg> <author> <branch> <commit_sha> [run_url]


STATUS=$1
COMMIT_MSG=$2
AUTHOR=$3
BRANCH=${4#refs/heads/}
COMMIT_SHA=$5
RUN_URL=$6

# Create JSON payload
if [ -n "$RUN_URL" ]; then
  RUN_LINK_BLOCK=',[{"tag": "text", "text": "Run: "}, {"tag": "a", "text": "View Failed Run", "href": "'"$RUN_URL"'"}]'
else
  RUN_LINK_BLOCK=""
fi

DATA=$(cat <<EOF
{
    "msg_type": "post",
    "content": {
        "post": {
            "zh_cn": {
                "title": "Update runbooks rules template in branch [${BRANCH}]: ${STATUS}",
                "content": [
                    [
                        {"tag": "text", "text": "Commit: "},
                        {"tag": "a", "text": "${COMMIT_MSG}", "href": "https://github.com/tidbcloud/runbooks/commit/${COMMIT_SHA}"}
                    ],
                    [
                        {"tag": "text", "text": "Authored by: ${AUTHOR}"}
                    ]
                    ${RUN_LINK_BLOCK}
                ]
            }
        }
    }
}
EOF
)

# Remove newlines for curl
DATA=$(echo "$DATA" | tr -d '\n' | tr -d '\r')

# Send notification
curl -X POST -H 'Content-Type: application/json' -d "$DATA" "$WEBHOOK_URL"
