#!/usr/bin/env bash

if [ $PROCESS_JIRA_TASK != "true" ]; then
    echo "No need to update jira mr link"
    exit 0
fi

if [[ "$CI_COMMIT_MESSAGE" =~ ^("Merge branch 'MOBAPP-")[0-9] ]] && [[ "$CI_COMMIT_BRANCH" != "develop" ]]; then
    echo "No need to update jira mr link (merging branch to develop)"
    exit 0
fi

if [ "$CI_PIPELINE_SOURCE" != "merge_request_event" ]; then
    echo "No need to update jira mr link (not merge request event)"
    exit 0
fi 

issue_mr_current_link=$(echo $issue_detail_json | python3 -c 'import json,sys;obj=json.load(sys.stdin);print(obj["fields"]["customfield_11302"])')
echo "task mr link from response: ${issue_mr_current_link}"

issue_mr_link="${CI_MERGE_REQUEST_PROJECT_URL}/-/merge_requests/${CI_MERGE_REQUEST_IID}"

if [ "$issue_mr_current_link" == "$issue_mr_link" ]; then
    echo "issue mr link in jira is up to date"
    exit 0
fi

echo "Updating issue mr link in jira"

http_response_code=$(curl --location --request PUT "https://jira.rutube.ru/rest/api/2/issue/$parsed_task_name" \
--header "Authorization: Bearer $JIRA_API_KEY" \
--header "Content-Type: application/json" \
--data-raw "{
    \"fields\": {\"customfield_11302\": \"${issue_mr_link}\"}
}" -o /dev/null -w '%{http_code}\n')

if [ "$http_response_code" == "204" ]; then
    echo "Issue mr link updated! - ${issue_mr_link}"
else
    echo "Error updating issue mr link"
    # exit 1
fi
