#!/bin/sh
set -euC

# Variables.
prog="$(basename "$0")"
dir="$(dirname "$0")"

# Were we run by git or manually?
if [ "$prog" = "git-multihook" ]
then
    # Set up hook symlinks and `*.d` directories.
    man githooks \
    | awk '/^[^ ]/{x=$0=="HOOKS"};x&&/^   [^ ]/' \
    | while read hook
    do
        if printf "%s\n" "$@" | grep -q '^'"$hook"'$'
        then
            continue
        fi
        if ! [ -e "$dir/$hook" ]
        then
            ln -s "$prog" "$dir/$hook"
            printf "%s\n" "$dir/$hook"
        fi
        if ! [ -e "$dir/${hook}.d" ]
        then
            mkdir -p "$dir/${hook}.d"
            printf "%s\n" "$dir/${hook}.d"
        fi
    done
else
    # Delegate to executable files in `*.d` directory.
    if ! [ -t 1 ]
    then
        stdin="$(cat)"
    fi
    for file in "$dir/${prog}.d/"*
    do
        if [ -x "$file" ]
        then
            if ! [ -t 1 ]
            then
                printf "%s\n" "$stdin" | "$file" "$@" || exit "$?"
            else
                "$file" "$@" || exit "$?"
            fi
        fi
    done
fi
