#!/bin/bash
#
# Under linux, this will watch all the files under ./solent and ./testing.
# When it detects a save, it will run the test suite. It's useful to run this
# in a window alongside your editor. This runs the test suite on each save.
#

NOW=$(date +%Y%m%d)
WATCHFILE=/tmp/$NOW

run_tests_within_venv() {
    pushd venv
    . bin/activate
    popd

    python3 run_tests.py

    echo '(fini)'
}

clear
echo "[watch]"

while [[ "1" == "1" ]]; do
    inotifywait -e close_write -r solent testing > $WATCHFILE 2>/dev/null
    #
    # Suggestions for improvements to this are welcome. What it's doing:
    # up the file that inotifywait writes to. If it sees a hidden file
    # (file beginning with a period) then it wants to do nothing. If
    # it's a non-hidden file, it wants to do something. It prints the
    # result of that calculation, which is what goes into $WORTH_RUNNING
    WORTH_RUNNING=$(echo "$WATCHFILE" | python3 -c '
import sys

watchfile_fname = input()

f_ptr = open(watchfile_fname)
lines = [l.strip() for l in f_ptr.readlines() if len(l) > 0]
f_ptr.close()
b_worth_running = False
for line in lines:
    tokens = line.split(" ")
    filename = tokens[2]
    if filename.startswith("."):
        continue
    b_worth_running = True
if b_worth_running:
    print("1")
else:
    print("0")
    ')
    if [[ "$WORTH_RUNNING" == "1" ]]; then
        echo ""
        echo ""
        echo ""
        echo ""
        echo ""
        echo "========================================================"
        echo "  `date`"
        echo "========================================================"
        echo ""
        run_tests_within_venv
    fi
done

