#!/usr/bin/env bash
set -euo pipefail

# If the branch name contains the issue number, it will append it to the
# commit message. Example:
#
#   BRANCH NAME               APPEND
#   feature/PLANET-3125-fix   PLANET-3125
#   planet-3125               PLANET-3125
#   some-name                 fail

COMMIT_MSG_FILE=$1
COMMIT_SOURCE=$2
COMMIT_MSG=$(<$COMMIT_MSG_FILE)

# If this is not a commit, exit successfully.
if [[ $COMMIT_SOURCE != "message" ]]; then
  echo "We are exiting as this is not a commit"
  exit 0;
fi

# Customize which branches should be skipped when
# prepending commit message.
BRANCHES_TO_SKIP=(master develop)

# Get current branch.
BRANCH_NAME=$(git symbolic-ref --short HEAD)

# Get planet4 branch.
PLANET_BRANCH_NAME=$(echo "$BRANCH_NAME" | awk 'match($0,/(PLANET|planet)-[0-9]*/) {print toupper(substr($0,RSTART,RLENGTH))}')

# If current branch is in the excluded list, nothing to do here, exit successfully.
if printf "%s\\n" "${BRANCHES_TO_SKIP[@]}" | grep -q "^$BRANCH_NAME$"
then
  exit 0
fi

# If commit message already includes planet4 issue, nothing to do here, exit successfully.
if [[ $COMMIT_MSG == *$PLANET_BRANCH_NAME* ]]; then
  exit 0;
fi

# If planet-xxx is not included in the branch name exit unsuccessfully.
if [[ -z "$PLANET_BRANCH_NAME" ]]; then
  echo "Error! Issue number is not part of the branch name or the commit message.";
  echo "Commit message should start with PLANET-xxx or branch name should contain planet-xxx or PLANET-xxx.";
  exit 1;
fi

# Finally prepend the planet4 branch name to the commit message.
sed -i.bak -e "1s/^/$PLANET_BRANCH_NAME /" "$COMMIT_MSG_FILE";
