#!/bin/bash

# Run the following command in the root of your project to install this pre-push hook:
# cp git-hooks/pre-push .git/hooks/pre-push; chmod 700 .git/hooks/pre-push

# ---- Run single_header build ---- #

MAKE_SINGLE_HEADER="cmake --build --preset=dev -t make_single_header && ./build/dev/tools/make_single_header ./include/libfork.hpp ./single_header/libfork.hpp"

eval $MAKE_SINGLE_HEADER

if [ $? -ne 0 ]; then
    echo "$MAKE_SINGLE_HEADER failed!"
    exit 1
fi

git add ./single_header/libfork.hpp 

# ---- Check if we actually have commits to push ---- #

commits=`git log @{u}..`
if [ -z "$commits" ]; then
    exit 0
fi

# ---- Check there are no untracked changes ---- #

pattern=$(git config --get hooks.prepush.sourcepattern)
if [ -z "$pattern" ]; then
    pattern="(?:(?:^|/)CMakeLists\.txt|\.hpp|\.cpp|\.cmake)$"
fi
    
files=$(git status -u --porcelain --no-column | sed "s/^?? //" | grep -P "$pattern")
if [ -n "$files" ]; then
    echo
    echo "ERROR: Preventing push with untracked source files:"
    echo
    echo "$files" | sed "s/^/    /"
    echo
    echo "Either include these files in your commits, add them to .gitignore"
    echo "or stash them with git stash -u."
    echo
    exit 1
fi

# ---- Run linter ---- #
    
LINT="cmake --build --preset=dev -t spell-check format-check"

eval $LINT

if [ $? -ne 0 ]; then
    echo "Lint: $LINT failed!"
    exit 1
fi

# ---- Run tests ---- #

TEST="cmake --build --preset=dev && ctest --preset=dev"

eval $TEST

if [ $? -ne 0 ]; then
    echo "Test: $TEST failed!"
    exit 1
fi

exit 0