#!/usr/bin/env bash

if [ $PROCESS_JIRA_TASK != "true" ]; then
    echo "No need to change task status"
    exit 0
fi

if [ "$issue_detail_json" == "" ]; then
    exit 0
fi

if [[ "$CI_COMMIT_MESSAGE" =~ ^("Merge branch 'MOBAPP-")[0-9] ]] && [[ "$CI_COMMIT_BRANCH" != "develop" ]]; then
    echo "No need to change task for merging branch - task: ${parsed_task_name}"
    exit 0
fi

while getopts f: flag
do
    case "${flag}" in
        f) FORCE_TO_READY_STATE=true;;
    esac
done

transactions_response_body=$issue_detail_json
transaction_to_status_id=$JIRA_STATUS_IN_REVIEW_ID

jira_issue_in_progress_id="10202"
jira_issue_improvement_id="11100"

fetch_transactions () {
    echo "Fetching task transactions"
    response=$(curl --location --request GET "https://jira.rutube.ru/rest/api/2/issue/${parsed_task_name}/transitions" \
    --header "Authorization: Bearer $JIRA_API_KEY" -w '%{http_code}' -s)

    http_response_code=$(echo $response | tail -c 4)
    echo "responseCode ${http_response_code}."

    if [ "$http_response_code" == "200" ]; then
        echo "TASK TRANSACTIONS FOUND"
    else
        echo "Error transactions for task $parsed_task_name not found"
        exit 1
    fi
    transactions_response_body=$(echo $response | sed 's/...$//')
}

do_transaction () {
    http_response_code=$(curl --location --request POST "https://jira.rutube.ru/rest/api/2/issue/${parsed_task_name}/transitions" \
    --header "Authorization: Bearer $JIRA_API_KEY" \
    --header 'Content-Type: application/json' \
    -d "{\"transition\":{\"id\":\"$1\"}}"  -o /dev/null -w '%{http_code}' -s)

    if [ "$http_response_code" == "204" ]; then
        echo "Task transaction finished"
        transaction_to_status_id=$JIRA_STATUS_IN_REVIEW_ID
    else
        echo "Error executing transaction with id '$1' for task $parsed_task_name"
        exit 0
    fi
}

issue_current_status_id=$(echo $issue_detail_json | python3 -c 'import json,sys;obj=json.load(sys.stdin);print(obj["fields"]["status"]["id"])')
echo "task issue status id: ${issue_current_status_id}"

if [ "$issue_current_status_id" != "$JIRA_STATUS_IN_REVIEW_ID" ] && [ "$issue_current_status_id" != "$jira_issue_in_progress_id" ] && [ "$issue_current_status_id" != "$jira_issue_improvement_id" ]; then
    transaction_to_status_id="$jira_issue_in_progress_id"
    transaction_id_to_execute=$(echo $transactions_response_body | python3 -c 'import json,sys;obj=json.load(sys.stdin);transactions=[x for x in obj["transitions"] if x["to"]["id"] ==  sys.argv[1] ];print(transactions[0]["id"] if transactions else "")' $transaction_to_status_id)
    if [ transaction_id_to_execute != "" ]; then
        echo "Task transaction to DOING"
        do_transaction $transaction_id_to_execute
        transaction_to_status_id=$JIRA_STATUS_IN_REVIEW_ID
    fi
    fetch_transactions
fi

transaction_id_to_execute=$(echo $transactions_response_body | python3 -c 'import json,sys;obj=json.load(sys.stdin);transactions=[x for x in obj["transitions"] if x["to"]["id"] ==  sys.argv[1] ];print(transactions[0]["id"] if transactions else "")' $transaction_to_status_id)

if [ "$issue_current_status_id" != "$transaction_to_status_id" ] && [ "$transaction_id_to_execute" != "" ]; then
    echo "TASK TRANSACTION to In REVIEW"
    do_transaction $transaction_id_to_execute
fi

echo "CI_PIPELINE_SOURCE: ${CI_PIPELINE_SOURCE}"
echo "FORCE_TO_READY_STATE: ${FORCE_TO_READY_STATE}"

if [ ! $FORCE_TO_READY_STATE ] && [ "$CI_PIPELINE_SOURCE" == "merge_request_event" ]; then
    echo "End of changing status of merge request task"
    exit 0
fi

fetch_transactions

issuetype_id=$(echo $issue_detail_json | python3 -c 'import json,sys;obj=json.load(sys.stdin);print(obj["fields"]["issuetype"]["id"])')
echo "task issue type id: ${issuetype_id}"

transaction_to_status_id=$JIRA_STATUS_WAITING_FOR_TEST_ID

if [ "$issuetype_id" == "$JIRA_TECHNICAL_ISSUE_ID" ]; then
    transaction_to_status_id=$JIRA_STATUS_DONE_ID
fi

transaction_id_to_execute=$(echo $transactions_response_body | python3 -c 'import json,sys;obj=json.load(sys.stdin);transactions=[x for x in obj["transitions"] if x["to"]["id"] ==  sys.argv[1] ];print(transactions[0]["id"] if transactions else "")' $transaction_to_status_id)

if [ "$transaction_id_to_execute" != "" ]; then
    echo "TASK TRANSACTIONS ID to execute is: ${transaction_id_to_execute}"
else
    echo "Error no transactions available for executing for task $parsed_task_name"
    exit 1
fi

echo "Updating task status to status Done or Waiting for tests"
do_transaction $transaction_id_to_execute

echo "end of change_jira_task_status.sh script execution"
