# -*- mode: sh; sh-shell: bash -*-
# vim: set ft=bash:
# shellcheck shell=bash
### Support for the entr file watcher

require git_lib

## Succeeds when 'entr' is available.
rule is_entr_installed: 'is_command_installed entr'

function entr_watch
{
    while ! git_ls_files -c --other | entr -c -s "sleep 0.25 ; $BAR_SELF $BARF_FILE $*"; do :; done
}

## Runs bar in a loop again whenever a file gets changed.
## Takes a target rule and its parameters as argument.
## Defaults to 'MAIN'.
rule entr_watch: is_entr_installed -

## Runs bar in a loop again whenever the git index gets changed.
## Takes a target rule and its parameters as argument.
## Defaults to 'MAIN'.
function entr_watch_git_index
{
    # shellcheck disable=2034
    local treehash="$BAR_PWD/.bar.$$.treehash"
    touch "$treehash"
    (
        export -f git_ls_files

        # shellcheck disable=2030
        declare -gxr treehash="$treehash"
        # shellcheck disable=2016
        echo "${GIT_INDEX_FILE:-$(git rev-parse --git-dir)/index}" | entr -s '
             new_hash=$(git_ls_files -c -s | sha1sum -)
             hash="$(<"$treehash")"
             if [[ "$new_hash" != "$hash" ]]; then
                echo "$new_hash" >"$treehash"
                clear
                $BAR_SELF $BARF_FILE $*
             fi
         '
    )

    # shellcheck disable=2031
    rule CLEANUP: -- "rm '$treehash'"
}
