#!/bin/sh

set -e

usage() {
	cat <<-EOT
	E: Invalid usage. Abort.

	Usage:

	    $0 {github_username} {github_reponame} {github_pr_url}
	EOT
}

# Skip e2e by default
require_e2e=false

GITHUB_USERNAME=$1
GITHUB_REPONAME=$2
GITHUB_PR_URL=$3

if test -z "${GITHUB_USERNAME}" ; then
	usage "$0"
	exit 2
elif test -z "${GITHUB_REPONAME}" ; then
	usage "$0"
	exit 2
elif test -z "${GITHUB_PR_URL}" ; then
	usage "$0"
	exit 2
fi

PR_NUMBER=$(echo "${GITHUB_PR_URL}" | sed -e 's,.*/,,')

pull_info_file=$(mktemp)
trap "rm -f ${pull_info_file}" EXIT

curl -s "https://api.github.com/repos/${GITHUB_USERNAME}/${GITHUB_REPONAME}/pulls/${PR_NUMBER}" > "${pull_info_file}"

# Keep the matching lines instead of simply looking at the exit
# code for debugging purposes
E2E_LABELS=$(jq -r '.labels[].name' < "${pull_info_file}" | grep --line-regexp --fixed-strings ci:e2e || true)

if test -n "${E2E_LABELS}" ; then
	echo "Honoring request to run E2E tests from pull request labels"
	exit 0
fi

TARGET_BRANCH=$(jq -r .base.ref < "${pull_info_file}")

case "${TARGET_BRANCH}" in
	master)
		if git --no-pager diff --name-only HEAD "origin/${TARGET_BRANCH}" |
			grep -q -E -f .ci/e2e_triggers
		then
			# There are changes in critical components, require e2e
			require_e2e=true
		fi
		;;

	release-*)
		# Require E2E for all changes going into a release branch
		require_e2e=true
		;;

	*)
		# The branch is not master or release, skip e2e
		require_e2e=false
		;;
esac

if ${require_e2e} ; then
	echo "Critical changes detected."
	exit 0
else
	echo "No critical changes detected."
	exit 1
fi
