#!/bin/bash

if [[ $# -ne 1 ]]
then
    echo "Usage: ./autocommit <FILE_PATH>"
    exit 1
fi

if ! [ -x "$(command -v inotifywait)" ]
then
    echo "This script requires 'inotify-tools'"
    exit 1
fi

if ! [ -x "$(command -v git)" ]
then
    echo "This script requires 'git'"
    exit 1
fi

FILE=$(basename "$1")
DIRECTORY=$(echo ${1::-"$((${#FILE} + 1))"})
COMMIT_MESSAGE="auto: $FILE changed"

if [ ! -d "$DIRECTORY/.git" ] || ! git -C "$DIRECTORY" rev-parse 2>/dev/null
then
    echo "'${DIRECTORY}' must be an initialised GIT directory"
fi

echo "Using GIT directory '${DIRECTORY}':"
echo
echo -e "Changes:\t$(git -C "$DIRECTORY" log --oneline|wc -l)"
echo -e "Last commit:\t$(git -C "$DIRECTORY" log -1 --format=format:%s)"
echo -ne "First change:\t$(git -C "$DIRECTORY" log --format=format:%aD | tail -1) "
echo "($(git -C "$DIRECTORY" log --format=format:%ar | tail -1))"
echo -ne "Last  change:\t$(git -C "$DIRECTORY" log -1 --format=format:%aD) "
echo "($(git -C "$DIRECTORY" log -1 --format=format:%ar))"
echo
echo "Now watching '${DIRECTORY}/${FILE}' for changes >> "

while true
do
    cd "$DIRECTORY"

    inotifywait -qq -e CLOSE_WRITE "$FILE"

    echo -n ?

    # Keep duplicate updates out
    sleep 1s

    git add "$FILE"

    # Bail if nothing to commit
    git diff --cached --quiet && continue

    echo -ne \\r\\a

    git commit -qm "$COMMIT_MESSAGE"

    echo "[$(date -Is)] File changed: $DIRECTORY/$FILE"
done
