#!/usr/bin/env sh

help() {
    cat <<EOF
An simple watch script, useful to see the changes in the document as it evolves.

USAGE:
    watch.sh [OPTIONS] [COMMAND]

OPTIONS:
    --help          | -h
                            Display this help and exit.

    --open [READER] | -o [READER]
                            Open the build PDF in READER before waiting for changes.
                            READER defaults to the READER environment variable or
                            'zathura' if the env variable is unset.
    --sleeptime [T] | -s [T]
                            How long to sleep between each build attempt in seconds. The
                            time defaults to 10 seconds.
ARGUMENTS:
    READER := [[echo "\${READER-zathura}"]]
                            The reader to open the build PDF with.

    T      := [[seq 1 100]]
                            The time to sleep between each build attempt.
EOF
}

reader=""
time="10"
for arg in "$@"; do
    case "$arg" in
    "--help" | "-h")
        help
        exit 0
        ;;

    "--open" | "-o")
        shift 1
        reader="$1"
        if [ -z "$reader" ]; then
            reader="${READER-zathura}"
        else
            shift 1
        fi
        ;;

    "--sleeptime" | "-s")
        shift 1
        time="$1"
        if [ -z "$time" ]; then
            time=10
        else
            shift 1
        fi
        ;;
    *)
        echo "'$1' is not a recognized option! See '--help' for more detail." 1>&2
        exit 1
        ;;
    esac
done

[ -n "$reader" ] && "$reader" ./build/%INIT_APPLICATION_NAME.pdf &

while true; do
    ./build.sh
    sleep "$time"
done