#!/usr/bin/env bash
# Extract the host where the server is running, and add the URL to the APIs
[[ $HOST =~ ^https?://[^/]+ ]] && HOST="${BASH_REMATCH[0]}/api/v4/projects/"

# Look which is the default branch
TARGET_BRANCH=`curl --silent "${HOST}${CI_PROJECT_ID}" --header "PRIVATE-TOKEN:${PRIVATE_TOKEN}" | python3 -c "import sys, json; print(json.load(sys.stdin)['default_branch'])"`;

release_name="release-v"
hotfix_name="hotfix-ISMO-"
remove_branch=true

function create_body_mergerequest () {
    
    #if [[ ${TARGET_BRANCH} = "master" ]]; then
    #remove_branch=false
    #fi
    
    echo ${CI_PROJECT_ID}
    echo ${CI_COMMIT_REF_NAME}
    echo ${TARGET_BRANCH}
    echo $remove_branch
    BODY="{
        \"id\": ${CI_PROJECT_ID},
        \"source_branch\": \"${CI_COMMIT_REF_NAME}\",
        \"target_branch\": \"${TARGET_BRANCH}\",
        \"remove_source_branch\": $remove_branch,
        \"title\": \"WIP: ${CI_COMMIT_REF_NAME}\"
    }";

}

function open_mergerequest () {
    
        curl -X POST "${HOST}${CI_PROJECT_ID}/merge_requests" \
            --header "PRIVATE-TOKEN:${PRIVATE_TOKEN}" \
            --header "Content-Type: application/json" \
            --data "${BODY}";

        echo "Opened a new merge request: WIP: ${CI_COMMIT_REF_NAME} and assigned to you";
}

if [[ ${CI_COMMIT_REF_NAME} =~ ^$release_name.+$ || ${CI_COMMIT_REF_NAME} =~ ^$hotfix_name.+$ ]]; then
create_body_mergerequest
open_mergerequest
sleep 1s
TARGET_BRANCH="master"
create_body_mergerequest
open_mergerequest
else
# Creates the body json of the merge request
create_body_mergerequest
# Open the merge request if not exist yet
open_mergerequest
fi
exit;