#!/usr/bin/env bash
#==========================================================================
#
#   Copyright Insight Software Consortium
#
#   Licensed under the Apache License, Version 2.0 (the "License");
#   you may not use this file except in compliance with the License.
#   You may obtain a copy of the License at
#
#          http://www.apache.org/licenses/LICENSE-2.0.txt
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.
#
#==========================================================================*/

egrep-q() {
  egrep "$@" >/dev/null 2>/dev/null
}

# Prepare a copy of the message:
#  - strip comment lines
#  - stop at "diff --git" (git commit -v)
commit_msg="$GIT_DIR/COMMIT_MSG"
sed -n -e '/^#/d' -e '/^diff --git/q' -e 'p;d' "$1" > "$commit_msg"

die() {
  echo 'commit-msg hook failure' 1>&2
  echo '-----------------------' 1>&2
  echo '' 1>&2
  echo "$@" 1>&2
  echo '
To continue editing, run the command
  git commit -e -F '"$commit_msg"'
(assuming your working directory is at the top).' 1>&2
  exit 1
}

# Check the first line for a standard prefix.
cat "$commit_msg" |
while IFS='' read line; do
  # Look for the first non-empty line.
  len=$(echo -n "$line" | wc -c)
  if test $len -gt 0; then
    # Look for valid prefixes.
    echo "$line" |
    egrep-q '^(Merge|Revert|BUG:|COMP:|DOC:|ENH:|PERF:|STYLE:|WIP:) ' ||
    die 'Start BRAINS commit messages with a standard prefix (and a space):
  BUG:    - fix for runtime crash or incorrect result
  COMP:   - compiler error or warning fix
  DOC:    - documentation change
  ENH:    - new functionality
  PERF:   - performance improvement
  STYLE:  - no logic impact (indentation, comments)
  WIP:    - Work In Progress not ready for merge
To reference Mantis issue XY, add " (#XY)" to the END of the FIRST line.'

    # Reject bug number reference that CDash rejects.
    echo "$line" |
    egrep-q '^BUG: [0-9][0-9]*\.' &&
    die 'Do not put a "." after the bug number:

  '"$line"

    # Done.  Skip rest of lines.
    break
  fi
done &&
rm -f "$commit_msg" || exit 1
