#!/bin/bash

# Setting pipefial
# e: Exit script immediately if any command returns a non-zero exit status.
# u: Exit script immediately if an undefined variable is used (for example, echo "$UNDEFINED_ENV_VAR").
# o pipefail: Ensure Bash pipelines return a non-zero status if any of the commands fail, rather than returning the exit status of the last command in the pipeline.
# x: Expand and print each command before executing.
set -Eeo pipefail

if [ "$BUILDKITE_PULL_REQUEST" == false ]; then
    echo "--- :sonarcloud: Get branch status in SonarCloud"
    PROJECTSTATUS=$(curl -X GET "https://sonarcloud.io/api/qualitygates/project_status?projectKey=bananatag_$REPO_NAME&branch=$BUILDKITE_BRANCH" \
    --header "Authorization: ${SONAR_AUTH_TOKEN}")

else
    echo "--- :sonarcloud: Get Pull Request status in SonarCloud"
    PROJECTSTATUS=$(curl -X GET "https://sonarcloud.io/api/qualitygates/project_status?projectKey=bananatag_$REPO_NAME&pullRequest=$BUILDKITE_PULL_REQUEST" \
    --header "Authorization: ${SONAR_AUTH_TOKEN}")
fi

echo "+++ :sonarcloud: SonarCloud Project Status:"
echo $PROJECTSTATUS | jq .

QGSTATUS=$(echo $PROJECTSTATUS | jq '.projectStatus.status' | tr -d '"') 

echo "--- :sonarcloud: Validate SonarCloud Quality Gates"
if [ "$QGSTATUS" = "OK" ]
then
    echo "✅"
    exit 0
else
    if [ "$QGSTATUS" = "ERROR" ]
    then
        echo "❌"
        echo "Look at the previous section to see the full project status!"
        exit 1
    fi
    echo "❔"
fi
