#!/bin/sh
#
# 1. get branch name, split by '/', get last part and save it as PREFIX
# 2. if commit message not starts with PREFIX, add PREFIX to start of the commit
# 3. match commit message with regex '^[A-Za-z]+-\d+'

COMMIT_MESSAGE=$(cat $1)

# add branch pattern to message if commit message not started with prefix, for example
# PREFIX_WITHOUT-SPACES: my commit message
if [[ ! $COMMIT_MESSAGE =~ ^[^[:space:]]+: ]]; then
    # get branch name
    BRANCH=$(arc info | grep '^branch:' | cut -b 9-)

    # split branch name and get last part
    IFS='/' read -ra PARTS <<< "$BRANCH"
    for i in "${PARTS[@]}"; do
        BRANCH=$i
    done

    # add branch name to commit message
    COMMIT_MESSAGE="$BRANCH: $COMMIT_MESSAGE"
fi

# check message by regex
if [[ ! $COMMIT_MESSAGE =~ ^[A-Za-z]+-[0-9]+ ]]; then
    echo >&2 commit message cannot be matched with ST task:
    echo >&2 "$COMMIT_MESSAGE"
    exit 1
fi

echo "$COMMIT_MESSAGE" > $1
