#!/bin/sh

branch=$(git rev-parse --abbrev-ref HEAD)

# Allow master and development
if [ "$branch" = "master" ] || [ "$branch" = "development" ]; then
  exit 0
fi

# Validate feature/* and bugfix/* branches
case "$branch" in
  feature/*|bugfix/*)
    name="${branch#*/}"

    # Name must not be empty
    if [ -z "$name" ]; then
      echo "ERROR: Branch '$branch' has an empty name after the prefix."
      exit 1
    fi

    # Only letters, digits, and dashes allowed
    if echo "$name" | grep -qE '[^a-zA-Z0-9-]'; then
      echo "ERROR: Branch '$branch' contains invalid characters."
      echo "       Only letters, digits, and dashes are allowed after the prefix."
      exit 1
    fi

    # No leading or trailing dashes
    if echo "$name" | grep -qE '^-|-$'; then
      echo "ERROR: Branch '$branch' must not start or end with a dash."
      exit 1
    fi

    # No consecutive dashes
    if echo "$name" | grep -q -- '--'; then
      echo "ERROR: Branch '$branch' must not contain consecutive dashes."
      exit 1
    fi

    # Max 25 characters excluding dashes
    name_no_dashes=$(echo "$name" | tr -d '-')
    char_count=${#name_no_dashes}
    if [ "$char_count" -gt 25 ]; then
      echo "ERROR: Branch '$branch': the name after the prefix is $char_count characters (excluding dashes), max is 25."
      exit 1
    fi

    exit 0
    ;;
esac

echo "ERROR: Branch name '$branch' does not follow the naming convention."
echo ""
echo "  Allowed formats:"
echo "    master"
echo "    development"
echo "    feature/{name}"
echo "    bugfix/{name}"
echo ""
echo "  Rules for feature/bugfix names:"
echo "    - Letters, digits, and dashes only (no spaces)"
echo "    - No leading, trailing, or consecutive dashes"
echo "    - Max 20 characters excluding dashes"
exit 1