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

ISSUE_TITLE="[image-scanning] Scan pipeline failure"
ISSUE_REPO="rancher/image-scanning"
ISSUE_LABELS="pipeline,pipeline/failure"
ISSUE_BODY="The image-scanning scan pipeline [#${DRONE_BUILD_NUMBER}](${DRONE_BUILD_LINK}) failed. Please check the pipeline error(s) and fix the issue(s), so the next daily scan can run successfully."
ISSUE_BODY_FILE="issue_content.txt"

echo "${ISSUE_BODY}" > "${ISSUE_BODY_FILE}"

# Check if there is an already closed issue
ISSUE=$(gh issue list -R "${ISSUE_REPO}" -S "${ISSUE_TITLE}" -s closed --json number --jq ".[].number")
if [[ -z "${ISSUE}" ]]
then
	# Otherwise, check if there is an open issue or not
	ISSUE=$(gh issue list -R "${ISSUE_REPO}" -S "${ISSUE_TITLE}" -s open --json number --jq ".[].number")
	if [[ -z "${ISSUE}" ]]
	then
		echo "==> There is no opened issue, let's open a new one"
		gh issue create -R "${ISSUE_REPO}" -t "${ISSUE_TITLE}" -F "${ISSUE_BODY_FILE}" -l "${ISSUE_LABELS}"
	else
		echo "==> There is an opened issue, let's update the existing one - ${ISSUE}"
		gh issue edit -R "${ISSUE_REPO}" -t "${ISSUE_TITLE}" -F "${ISSUE_BODY_FILE}" --add-label "${ISSUE_LABELS}" ${ISSUE}
	fi
else
	echo "==> There is a closed issue, let's reopen it - ${ISSUE}"
	gh issue reopen -R "${ISSUE_REPO}" "${ISSUE}"
	gh issue edit -R "${ISSUE_REPO}" -t "${ISSUE_TITLE}" -F "${ISSUE_BODY_FILE}" --add-label "${ISSUE_LABELS}" "${ISSUE}"
	
fi

