#!/usr/bin/env bash

set -e

cmd=$(basename $0)

sub_help(){
    echo "Usage: $cmd <sub-command> [options]"
    echo "Sub-commands:"
    echo "    help              Show help"
    echo "    checkout          Checkout code from git"
    echo "    compile           Compile java code"
    echo "    sonar-scan        Run sonar scanner"
    echo "    send-email        Send email after stage/pipeline"
    echo ""
    echo "For help with each sub-command run:"
    echo "$cmd <sub-command> -h|--help"
    echo ""
}

sub_checkout(){
    echo "--------------CHECKING OUT GIT CODE--------------------"
    cd /root/GitlabRunner/repo/
    ls
    rm -rf ./spring-ci-advanced
    git config --global user.name 'truongbb96'
    git config --global user.email 'truongbb@itsol.vn'
    git clone https://truongbb96:hoanghuynh0801@git.myitsol.com/truongbb96/spring-ci-advanced.git
    cd ./spring-ci-advanced
    echo "--------------DONE CHECKING OUT GIT CODE--------------------"
}

sub_compile(){
    # mvn install
    _docker_mvn compile -DskipTests

}

sub_sonar-scan(){
#    /root/sonar-scanner/bin/sonar-scanner
    rm -rf ./target/*
    mvn clean --settings settings.xml package sonar:sonar \
        -Dsonar.projectName='SpringCIAdvanced' \
        -Dsonar.projectKey='spring-ci-advanced'
#    curl -s -w "\n%{http_code}" 'http://192.168.1.210:9000/api/qualitygates/project_status?projectKey=spring-ci' | {
#        echo "1111111111111111111111"
#        read body
#        read code
#        echo ${code}
#        jq .name <<< "$body"
#    }
#    response=$(curl -s -w "\n%{http_code}" 'http://192.168.1.210:9000/api/qualitygates/project_status?projectKey=spring-ci')
#    response=(${response[@]}) # convert to array
#    code=${response[-1]} # get last element (last line)
#    body=${response[@]::${#response[@]}-1} # get all elements except last
#    bodyRes=$(echo $body | jq '.bodyRes')
#    echo $code
#    echo "body: "$bodyRes
    res=$( curl --request POST \
        --url http://192.168.1.210:9000/api/qualitygates/project_status?projectKey=spring-ci \
        --header 'cache-control: no-cache' --header 'content-type: application/json' | jq)
    echo "${res}"
}

sub_send-email(){
    echo "TODO - send email"
}

_docker_mvn() {
    docker run -i --rm \
        -v "$PWD:/usr/src/" \
        -v "$HOME/.m2:/root/.m2" \
        -w /usr/src/ \
		maven:3.6.1-jdk-11 \
        mvn -U clean $@
}


sub_command=$1

case sub_command in
    "" | "-h" | "--help")
        sub_help
        ;;
    *)
        shift
        sub_${sub_command} $@
        if [[ $? = 127 ]]; then
            echo "Error: '$sub_command' is not a known sub-command." >&2
            echo "Run '$cmd --help' for a list of known sub-commands." >&2
            exit 1
        fi
        ;;
esac