#!/usr/bin/env bash

INPUT_FILE=$1
START_LINE=$(head -n1 "$INPUT_FILE")
PATTERN='^(HMIG|COMP)-[0-9]+'  # Pattern to match the branch name
BRANCH_NAME=$(git symbolic-ref --short HEAD)

echo "Commit on branch: $BRANCH_NAME"

# Check if the commit is a merge commit
IS_MERGE=$(git rev-parse --verify MERGE_HEAD 2>/dev/null)

# Prevent direct commits to main
if [[ "$BRANCH_NAME" == "main" ]]; then
    if [[ -z "$IS_MERGE" ]]; then
        echo "Error: Direct commits to 'main' are not allowed. Only merge commits are permitted." >&2
        exit 1
    else
        echo "Merge commit detected. Proceeding with commit."
        exit 0
    fi
fi

# Validate feature branch name format
if [[ ! $BRANCH_NAME =~ $PATTERN ]]; then
    echo "Error: Branch name must start with 'HMIG-XXX' or 'COMP-XXX' where XXX is a number." >&2
    exit 1
fi

PREFIX=$(echo "$BRANCH_NAME" | sed -n "s/^\(HMIG-[0-9]\+\|COMP-[0-9]\+\).*$/\1/p")

# Validate commit message prefix
if ! [[ "$START_LINE" =~ $PREFIX ]]; then
    echo "Error: Commit message must start with $PREFIX."
    exit 1
fi
