#!/usr/bin/env bash
#
# Git commit-msg hook to enforce coding standards
#
# @author      Steve Talbot
# @copyright   Copyright (c) Solviq Ltd 2016-9
# @license     MIT

# This script is symlinked from a vendor directory
BASEDIR=`git rev-parse --show-toplevel`
matched=0

# Ignore merge commits
if [ -f "$BASEDIR/.git/MERGE_MSG" ]; then
    echo "This appears to be a merge commit"
    exit 0
fi

# Sanity check
if [ ! -f "$1" ]; then
    echo "Commit message file \"$1\" not found!"
    exit 2
fi

# Github issue reference, e.g. #123 or another/repo#123
if grep -P '(?<![/\w.-])(?:\w[\w.-]*/\w[\w.-]*)?#[1-9]\d*(?![\w.-])' "$1"; then
    ((matched++))
fi

# Atlassian Jira issue reference, e.g. CONDUIT-123
if grep -P '(?<![/\w.-])([A-Z][A-Z0-9_]+-[1-9][0-9]*)(?![\w.-])' "$1"; then
    ((matched++))
fi

# Allow commit?
if (( matched < 1 )); then
    echo "Your commit message does not appear to contain a ticket number"
    exit 1
fi
exit 0
