#!/bin/bash
source "$ROOT_PATH"/scripts/common.sh
set -eo pipefail

echo_green_bg "Getting JIRA ticket ID from branch name"

fail_on_empty="${FAIL_ON_EMPTY_JIRA}"
branch="${BRANCH}"

if [ -z "$branch" ]; then
    if [ "$fail_on_empty" == "true" ]; then
        handle_error "BRANCH variable is empty"
    else
        echo_yellow "BRANCH variable is empty. Proceeding without setting JIRA_TICKET."
        exit 0
    fi
fi

ticket_id=$(echo $branch | grep -Eo "^P81-[0-9]+")

if [ -z "$ticket_id" ]; then
    if [ "$fail_on_empty" == "true" ]; then
        handle_error "ERROR - no Jira ticket id on branch name: $branch"
    else
        echo_yellow "No JIRA ticket ID found in branch name: $branch. Proceeding without setting JIRA_TICKET."
    fi
else
    echo "JIRA ticket ID found: $ticket_id. Adding to GITHUB_ENV."
    echo "JIRA_TICKET=$ticket_id" >> $GITHUB_ENV || handle_error "Failed to write JIRA_TICKET to GITHUB_ENV"
fi