#!/usr/bin/env bash
set -e

echo "GitHub event path: ${GITHUB_EVENT_PATH}"
echo "JQ: $(which jq)"


# Skip the label check if we do not have a GitHub event path
if [[ -f "${GITHUB_EVENT_PATH}" ]] && jq -e '.pull_request?.labels[]?.name | select(. == "changelog/no-changelog")' "${GITHUB_EVENT_PATH}";
then
    PR_TITLE=$(jq -er '.pull_request?.title' "${GITHUB_EVENT_PATH}")

    if [[ "${PR_TITLE}" == "fix"* ]];
    then
        echo "Fix PRs must have a changelog entry, remove the 'changelog/no-changelog' label"
        echo "Use 'reno new <slug>' to add a new note to 'releasenotes/notes'"
        exit 1
    fi

    echo "PR has label 'changelog/no-changelog', skipping validation"
    exit 0
fi

if [[ -f "${GITHUB_EVENT_PATH}" ]];
then
    # If we have an event, grab the PR base ref from the event data
    BASE_REF="$(jq -er '.pull_request?.base.ref' "${GITHUB_EVENT_PATH}")"
    # Make sure the ref we have starts with `origin/`
    if ! [[ $BASE_REF = origin/* ]];
    then
        BASE_REF="origin/${BASE_REF}"
    fi
elif [ -x "$(command -v git)" ]; then
    BASE_REF="$(git rev-parse --abbrev-ref origin/HEAD)"
else
    # If we are running outside a GitHub action, default to `1.x`
    BASE_REF="origin/${GITHUB_BASE_REF:-1.x}"
fi
echo "Base ref: ${BASE_REF}"

# Check if they added a new file or renamed a file in releasenotes/notes
if git diff --name-only --diff-filter=AR "${BASE_REF}" | grep "^releasenotes/notes";
then
    echo "New release note found, success"
    exit 0
else
    echo "Release note not found."
    echo "Use 'reno new <slug>' to add a new note to 'releasenotes/notes', or add the label 'changelog/no-changelog' to skip this validation"
    exit 1
fi
