#!/bin/sh
 
if git rev-parse --verify HEAD >/dev/null 2>&1
then
        against=HEAD
else
        # Initial commit: diff against an empty tree object
        against=4b825dc642cb6eb9a060e54bf8d69288fbee4904
fi
 
checkBash() 
{
    local file=$1
    echo checking for 'version' in $file
    now=`date +'%Y-%m-%d %R'`
    sed -i "s/^\(#.*\)version: .*/\1version: $now/" $file
    sed -i "s/^\(#.*\)Version: .*/\1Version: $now/" $file
    git add $file
}

# Set (Last Modified: <date>) in CHANGELOG.md
checkChangelog()
{
    local file=$1
    echo checking for 'Last Modified' in $file
    now=`date +'%Y-%m-%d'`
    sed -i "s/\(Last Modified: .*\)/\(Last Modified: $now\)/" $file
    git add $file
}

checkConfiguration() 
{
    local file=$1
    echo checking for '# Version:' in $file
    now=`date +'%Y-%m-%d %R'`
    sed -i "s/# version: .*/# version: $now/" $file
    sed -i "s/# Version: .*/# Version: $now/" $file
    git add $file
}

checkWhitespace()
{
    local file=$1
    echo checking for whitespace errors in $file
    local myTabs=$(grep -P '\t' $file | wc -l)
    if [ $myTabs -eq 0 ]; then
        echo -e "\e[32mFine zero tabs in $file\e[0m"
    else
        echo -e "\e[31m → Shit, multiple Tabs ($myTabs) in $file \e[0m"
        # exit 42
    fi
}

for FILE in `exec git diff --cached --name-only  --diff-filter=ACMR` ; do
        # Fix them!
        case $FILE in
                *.java)
                        echo checking @version in $FILE
                        now=`date +'%d.%m.%Y %R'`
                        sed -i "s/@version .*/@version $now/" $FILE
                        checkWhitespace $FILE
                        git add $FILE
                        ;;
                *.sh|*.profile)
                        checkBash $FILE
                        ;; 
                CHANGELOG.md)
                        checkChangelog $FILE
                        ;;
                */template.d/*|*.conf|*/config.properties)
                        checkConfiguration $FILE
                        ;;
                *.*)
                        echo "ignoring $FILE"
                        ;;
                *)
                        checkBash $FILE
                        ;;
        esac
done
 
exit
