#!/usr/bin/env bash
#
# Git post-commit hook to update the CONTRIBUTORS file
#
# @author      Steve Talbot
# @copyright   Copyright (c) Solviq Ltd 2016-2021
# @license     MIT

# This script is symlinked from a vendor directory
BASEDIR=$(git rev-parse --show-toplevel)
pushd "$BASEDIR" >/dev/null || exit 2

for file in CONTRIBUTORS*; do
    if [ ! -f "$file" ]; then
        continue;
    fi

    echo "Updating $file file to reflect latest commits"

    tempFileWithCurrentContents="$(mktemp)"
    cp $file "$tempFileWithCurrentContents"

    true >$file
    skipToBlankLine=0
    while read -r line; do
        if [ -z "$line" ]; then
            skipToBlankLine=0
        fi
        if [[ $skipToBlankLine -eq 0 ]]; then
            echo "$line" >>$file
        fi
        if [[ "$line" =~ \[//\]:\ *\#\ *\(autogenerated-authors\) ]]; then
            git shortlog --summary --numbered HEAD |cut -f2 |sed -e 's/^/- /' >>$file
            skipToBlankLine=1
        fi
    done <"$tempFileWithCurrentContents"

    rm "$tempFileWithCurrentContents"

    git add $file
done


if [ -n "$(git status --porcelain)" ]; then
    mv "$0" "$0-disabled"
    git commit --no-edit --no-verify --amend
    mv "$0-disabled" "$0"
fi

popd >/dev/null || exit 2
