#!/usr/bin/env bash

echo "--> find jira task started <--"
echo "--> Job id ${CI_JOB_ID} <--"

if [ "$CI_PIPELINE_SOURCE" == "pipeline" ] || [ $CI_COMMIT_TAG ]; then
    exit 0
fi

text_to_parse=""
if [[ "$CI_COMMIT_MESSAGE" =~ ^("Merge branch 'MOBAPP-")[0-9] ]]; then
    text_to_parse=${CI_COMMIT_MESSAGE}
elif [ "$CI_PIPELINE_SOURCE" == "merge_request_event" ]; then
    text_to_parse=${CI_MERGE_REQUEST_TITLE}
else
    text_to_parse=$CI_COMMIT_BRANCH
fi

#parsed_task_name=${mr_title%%[:. ]*}
export parsed_task_name=$(echo $text_to_parse | sed 's/\(MOBAPP-\)\([0-9]*\)/\n&\n/g' | sed -n '/^\(MOBAPP-\)\([0-9]*\)/p' | head -1)

echo "title $text_to_parse"
echo "parsed_task_name $parsed_task_name"

if [ "$parsed_task_name" != "" ]; then
    echo "parsed_task_name is: ${parsed_task_name}"

    response=$(curl --location --request GET "https://jira.rutube.ru/rest/api/2/issue/${parsed_task_name}?fields=customfield_11302,status,issuetype,summary&&expand=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 FOUND"
        echo "SUCCESS"
        export issue_detail_json=$(echo $response | sed 's/...$//')
    else
        echo "Error task $parsed_task_name not found"
    fi
else
    echo "No task name found"
fi

echo "end fetching task details ${parsed_task_name}"
echo "end of find_jira_task.sh script execution"
