#!/bin/bash
#
# Intended for use in CI, for -rhel branches: check git PR, barf if no jira links
#

ME=$(basename $0)

set -e

# Github label which allows overriding this check
OVERRIDE_LABEL="No Jira Link"

# Only -rhel branches need jira links
BRANCH_REGEX="v.*-rhel"

LINK_REGEX="Fixes:?[[:space:]]+https://issues.redhat.com/[[:alnum:]/-]*"

if [[ ! "${DEST_BRANCH}" =~ $BRANCH_REGEX ]]; then
    exit 0
fi

if [[ "${CIRRUS_CHANGE_MESSAGE}" =~ $LINK_REGEX ]]; then
    exit 0
fi

# Nope. Only allow if the github 'No Jira Link' label is set
if [[ -z "$CIRRUS_PR" ]]; then
    if [[ ! "$CIRRUS_BRANCH" =~ pull ]] || [[ -n "$CIRRUS_TAG" ]]; then
        echo "Warning: $ME only intended for use on PRs in CI"
        exit 0
    fi
    echo "$ME: cannot query github: \$CIRRUS_PR is undefined" >&2
    exit 1
fi

if [[ -z "$CIRRUS_REPO_CLONE_TOKEN" ]]; then
    echo "$ME: cannot query github: \$CIRRUS_REPO_CLONE_TOKEN is undefined" >&2
    exit 1
fi

query="{
  \"query\": \"query {
  repository(owner: \\\"containers\\\", name: \\\"podman\\\") {
    pullRequest(number: $CIRRUS_PR) {
      labels(first: 100) {
        nodes {
          name
        }
      }
    }
  }
}\"
}"

result=$(curl -s -H "Authorization: bearer $CIRRUS_REPO_CLONE_TOKEN" -H "Accept: application/vnd.github.antiope-preview+json" -H "Content-Type: application/json" -X POST --data @- https://api.github.com/graphql <<<"$query")

labels=$(jq -r '.data.repository.pullRequest.labels.nodes[]?.name' <<<"$result")

if grep -F -x -q "$OVERRIDE_LABEL" <<<"$labels"; then
    # PR has the label set
    exit 0
fi

cat <<EOF
$ME: PR does not include required references to Jira issues

Please add a reference to the related Jira ticket(s) by adding to the
description of the PR something like:

Fixes: https://issues.redhat.com/browse/RHEL-50507

You can use multiple lines like this, but only one issue per line.

If your commit really, truly does not need a jira link, you can proceed
by asking a repo maintainer to set the '$OVERRIDE_LABEL' github label.
This will only be done when there's no reasonable alternative.
EOF

exit 1
