#!/usr/bin/env bash

# in case that post-commit hook should not run (WAKE_SKIP_POST_COMMIT_HOOK is set)
# or pre-commit hook did not run prior to this hook ('.stash-id' does not exist)
# just exit the hook

if [[ -n "$WAKE_SKIP_POST_COMMIT_HOOK" || ! -e .stash-id ]]; then
    exit 0
fi

# there may be unstaged changes that were stashed in the pre-commit hook
# try to pop them from the stash
function pop_stash()
{
    # check if the top entry on the stash has the message matching the content of '.stash-id' file
    # if it matches, there were unstaged changes prior to the commit that should be popped from the stash now
    # in the other case there were no unstaged changes
    git stash list -n 1 | grep -f .stash-id >/dev/null 2>&1

    if [ $? -eq 0 ];
    then
        # this command may introduce merging conflicts
        # this is an expected behavior
        git stash pop >/dev/null
    fi
    # delete temporary .stash-id file anyway
    rm .stash-id
}

# add all changes made by 'black' and other pre-commit tools as a fixup commit
export WAKE_SKIP_POST_COMMIT_HOOK=1
git add -u -- wake wake_detectors wake_printers tests
git commit --fixup='HEAD' --no-verify >/dev/null
unset WAKE_SKIP_POST_COMMIT_HOOK

pop_stash;