#!/bin/bash
#
# An example hook script to prepare the commit log 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.
#

JIRA_MATCH='[A-Z][A-Z_0-9]\+-[0-9]\+'

BRANCH_NAME=$(git symbolic-ref --short HEAD)
JIRA_STR=$(echo $BRANCH_NAME |grep -oh $JIRA_MATCH)

COMMIT_EDITMSG="$(cat "$1")"

PREFIX_NAME='^\(feature\|release\|bugfix\|hotfix\)/'

if [ -z "$BRANCHES_TO_SKIP" ]; then
  BRANCHES_TO_SKIP='^\(master\|develop\|release\|test\)$'
fi

is_branch_empty() {
  if [ -z "$BRANCH_NAME" ]; then 
    echo "Branch name: \"$BRANCH_NAME\" should not be Empty!"
    exit 1
  fi
}

is_branch_excluded() {
  local branch_excluded=$(echo "$BRANCH_NAME" | grep "$BRANCHES_TO_SKIP")
  if [ -n "$branch_excluded" ]; then
    echo "warning: Branch ${BRANCH_NAME} should not be changed locally! ⚠️ "
    exit 0
  fi
}

is_branch_has_prefix_name() {
  local branch_with_prefix_name=$(echo "$BRANCH_NAME" | grep "$PREFIX_NAME")
  if [ -z "$branch_with_prefix_name" ]; then
    echo -e "Branch name: \"$BRANCH_NAME\" format error. Please fix it !!! ✏️ .\nCorrect branch name format is as follows: [feature | release | bugfix | hotfix]/JIRA-xxxx-brief-description."
    echo -e "Branching model: https://confluence.atlassian.com/bitbucketserver/using-branches-in-bitbucket-server-776639968.html"
    exit 1
  fi
}
    
is_branch_has_jira() {
  local branch_with_jira=$(echo "$BRANCH_NAME" | grep "$JIRA_MATCH")
  if [ -z "$branch_with_jira" ]; then
    echo "Branch name: \"$BRANCH_NAME\" does not match JIRA format. Please change it !!! ✏️ "
    exit 1
  fi
}

pick_real_commit_msg() {
  local msg_tempfile="$(mktemp)"
  echo "$1" &> "$msg_tempfile"
  local temp_msg=`sed -e '/# Everything below will be removed\./,$ d' \
    -e '/^#/d' \
    -e '/^[[:space:]]*$/d' \
    "$msg_tempfile"`
  rm "$msg_tempfile"
  echo "$temp_msg"
}

is_commit_msg_empty() {
  local commit_msg=$(pick_real_commit_msg "$COMMIT_EDITMSG")
  if [ -z "$commit_msg" ]; then
    echo "Commit message should not be Empty! Write Sth about the commit. ✏️ "
    exit 1
  fi
}

is_branch_already_in_commit() {
  local branch_in_commit=$(pick_real_commit_msg $1 | grep -c "$JIRA_STR")
  if [ $branch_in_commit -ge 1 ]; then
    exit 0
  fi
}

is_branch_empty
is_commit_msg_empty
is_branch_excluded
is_branch_has_jira
is_branch_has_prefix_name
is_branch_already_in_commit "$COMMIT_EDITMSG"

echo "$JIRA_STR" "$(cat "$1")" > $1

