#!/bin/bash -e
#
# This hook adds a comment for guidance about the commit message
# format on top of the default commit message.
#
# Called by "git commit" with the name of the file that has the
# commit message, followed by the description of the commit
# message's source.	The hook's purpose is to edit the commit
# message file.	If the hook fails with a non-zero status,
# the commit is aborted.

# shellcheck disable=SC2034,SC2312

COMMIT_MSG_FILE=$1
COMMIT_SOURCE=$2
SHA1=$3

# Function to test if a string starts with another string
beginswith() {
  case $2 in
    ("$1"*) return 0 ;;
    (*)     return 1 ;;
  esac
}

original=$(cat "${COMMIT_MSG_FILE}")

if beginswith $'\n#' "${original}"; then

  # Find common path prefix of changed files
  path=""
  count=0
  common=""

  while read -r file; do
    if [ -z "${common}" ]; then
      common="${file}"
      count=${#file}
    else
      while [ "${count}" -gt 0 ]; do
        prefix=${file:0:$count}
        common_prefix=${common:0:$count}
        [ "${prefix}" = "${common_prefix}" ] && break
        count=$((count - 1))
      done
    fi
  done <<EOF
$(git -P diff --cached --name-only -r)
EOF

  [ "${count}" -gt 0 ] && path="${common:0:$count}" || path=""

  # Clean up path info (e.g., remove .local/bin/scripts)
  path=$(echo "${path}" | sed 's|.local/bin/scripts|bin|')

  # Remove numeric prefixes like "2-box/" → "box/"
  # shellcheck disable=SC2249
  case "${path}" in
    [0-9]-*) path="${path#*-}" ;;
  esac

  {
    # Simplify path and add to commit message
    echo "${path}" | sed 's|^\.||;s|\.\([a-z]*\)$||;s|[/_-]\?$|: |'
    echo "${original}"
  } > "${COMMIT_MSG_FILE}"

fi
