#!/usr/bin/env bash

set -e
set -x

if [[ "$ZULIP_BOT_KEY" != "" && "$GITHUB_REPOSITORY" == "zulip/zulip" ]]; then
    BRANCH="$(python3 -c 'import sys; print(sys.argv[1].split("/")[-1])' "$GITHUB_REF")"
    URI_ESCAPED_TOPIC="$(python3 -c 'import sys; import urllib.parse; print(urllib.parse.quote(sys.argv[1]))' "$BRANCH failing")"
    curl -fL -H "Content-Type: application/json" \
        -X POST -i 'https://chat.zulip.org/api/v1/external/circleci?api_key='"$ZULIP_BOT_KEY"'&stream=automated%20testing&topic='"$URI_ESCAPED_TOPIC" \
        -d '{"payload": { "branch": "'"$BRANCH"'", "reponame": "'"$GITHUB_REPOSITORY"'", "status": "failed", "build_url": "'"$GITHUB_SERVER_URL/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID"'", "username": "'"$GITHUB_ACTOR"'"}}'
fi
