#!/usr/bin/env bash
#
# blame(ken)
#
# this runs "mvn verify sonar:sonar" with appropriate environment, params, AWS credentials, etc...
#
# you must export SONAR_TOKEN in your default shell config from https://sonarcloud.io/account after joining Sonarqube organization "netfoundry"
#

set -e          # raise exception if error
set -u          # raise exception if unset
set -o pipefail # raise exceptions in pipes

BASENAME=$(basename $0)
WORKDIR=$(cd $(dirname $0);pwd -P;)
cd $WORKDIR

unset   AWS_SECURITY_TOKEN \
        AWS_SESSION_TOKEN \
        AWS_ACCESS_KEY \
        AWS_SECRET_KEY \
        AWS_ACCESS_KEY_ID \
        AWS_SECRET_ACCESS_KEY \
        AWS_SHARED_CREDENTIALS_FILE \
        AWS_CREDENTIAL_PROFILES_FILE

export  AWS_CREDENTIAL_PROFILES_FILE=$WORKDIR/aws-credentials \
        SPRING_PROFILES_ACTIVE=test

# if the standard var SONAR_TOKEN is null then try to find the token in
# a non-standard var SONAR_ACCESS_KEY
[[ ! -z ${SONAR_TOKEN:=${SONAR_ACCESS_KEY:-}} ]] || {
        echo "ERROR: SONAR_TOKEN is not defined"
        exit 1
}

# check java version
expected_version=17
if [[ -n ${JAVA_HOME-} ]] && [[ -x "$JAVA_HOME/bin/java" ]];  then
    _java="$JAVA_HOME/bin/java"
elif [[ -n $(type -p java) ]]; then
    _java=java
else
    echo "Missing Java!  Set JAVA_HOME environment variable to the path to a JDK."
    exit 1
fi

version=$("$_java" -version 2>&1 | awk -F '"' '/version/ {print $2}')
if [[ "$version" < $expected_version ]]; then
    echo "This project requires Java $expected_version, but the current JDK version is $version"
    echo "Set JAVA_HOME to the directory of a $expected_version JDK."
    exit 1
fi
# end check java version

[[ $# -gt 0 ]] && {
        echo "WARN: Passing Maven options: $*" >&2
}
./mvnw verify sonar:sonar -Dsonar.branch.name="$(git rev-parse --abbrev-ref HEAD)" $@
