#
# Copyright Super iPaaS Integration LLC, an IBM Company 2024
#
echo "Adding labels"
source "${ONE_PIPELINE_PATH}"/tools/get_repo_params

APP_TOKEN_PATH="./app-token"
PR_URL=$(get_env PR_URL "")
PR_NUMBER=$(echo "$PR_URL" | grep -oP '(?<=pulls/)[0-9]+')
LABEL_TO_CHECK=prv_success
echo "$PR_NUMBER"
read -r APP_REPO_NAME APP_REPO_OWNER APP_SCM_TYPE APP_API_URL < <(get_repo_params "$(load_repo app-repo url)" "$APP_TOKEN_PATH")

RESPONSE=$(curl -s -H "Authorization: Bearer $(cat ${APP_TOKEN_PATH})" \
-H "Accept: application/vnd.github+json" \
"${APP_API_URL}/repos/${APP_REPO_OWNER}/${APP_REPO_NAME}/issues/$PR_NUMBER/labels")

# Check if label exists
if echo "$RESPONSE" | jq -e ".[] | select(.name == \"$LABEL_TO_CHECK\")" > /dev/null; then
  echo "Label '$LABEL_TO_CHECK' exists."
  curl -X DELETE -H "Authorization: Bearer $(cat ${APP_TOKEN_PATH})" \
    -H "Accept: application/vnd.github+json" \
     "${APP_API_URL}/repos/${APP_REPO_OWNER}/${APP_REPO_NAME}/issues/$PR_NUMBER/labels/$LABEL_TO_CHECK"
  curl -X POST -H "Authorization: Bearer $(cat ${APP_TOKEN_PATH})" -H "Accept: application/vnd.github+json" -d '{"labels": ["prv_success"]}' "${APP_API_URL}/repos/${APP_REPO_OWNER}/${APP_REPO_NAME}/issues/$PR_NUMBER/labels"   
else
  echo "Label '$LABEL_TO_CHECK' does not exist."
  curl -X POST -H "Authorization: Bearer $(cat ${APP_TOKEN_PATH})" -H "Accept: application/vnd.github+json" -d '{"labels": ["prv_success"]}' "${APP_API_URL}/repos/${APP_REPO_OWNER}/${APP_REPO_NAME}/issues/$PR_NUMBER/labels"
fi

