#!/bin/bash

## Put me in an empty directory.  Run me by listing the paths to the
## various makes that you want to compare as arguments.  Files like
## hello{,.c,.f} get touched and removed, so they'd better not already
## exist and contain something important!

function trials () {
    printf '\n\n\n\n'
    cat Makefile

    local input DIGIT
    for input in "${!INPUTS[@]}" ; do
        DIGIT["$input"]=0
    done

    while true ; do
        local RMS TOUCHES
        RMS=()
        TOUCHES=()
        for input in "${!INPUTS[@]}" ; do
            if ((DIGIT["$input"] > 0)) ; then
                TOUCHES+=("${INPUTS["$input"]}")
            else
                RMS+=("${INPUTS["$input"]}")
            fi
        done
        printf '\n'

        local cmd
        for cmd in "$@" ; do
            printf '\n'

            if [ "${#RMS[@]}" -gt 0 ] ; then
                echo '$' rm -f "${RMS[@]}"
                rm -f "${RMS[@]}"
            fi
            if [ "${#TOUCHES[@]}" -gt 0 ] ; then
                echo '$' touch "${TOUCHES[@]}"
                touch "${TOUCHES[@]}"
            fi
            printf '$ %s -rR\n' "$cmd"
            "$cmd" -rR
        done

        local ended=yes
        for input in "${!INPUTS[@]}" ; do
            if ((++DIGIT["$input"] < 2)) ; then
                unset ended
                break
            fi
            DIGIT["$input"]=0
        done

        if [ "$ended" ] ; then break ; fi
    done

    rm -f "${INPUTS[@]}"
}




cat > Makefile <<'EOF'
all: hello.tsk
%.tsk: %.c; $(info $@ from $<)
%.tsk: %.f; $(info $@ from $<)
unrelated: hello.c
EOF
INPUTS=(hello.c hello.f)
trials "$@"

cat > Makefile <<'EOF'
all: hello.tsk
%.tsk: %.c; $(info $@ from $<)
%.tsk: %.f; $(info $@ from $<)
EOF
INPUTS=(hello.c hello.f)
trials "$@"

cat > Makefile <<'EOF'
all: hello.tsk
hello.tsk: hello.c
%.tsk: %.c; $(info $@ from $<)
%.tsk: %.f; $(info $@ from $<)
EOF
INPUTS=(hello.c hello.f)
trials "$@"

cat > Makefile <<'EOF'
all: hello.tsk
%.tsk: %; $(info $@ from $<)
unrelated: hello
EOF
INPUTS=(hello)
trials "$@"

cat > Makefile <<'EOF'
all: hello.tsk
%.tsk: %; $(info $@ from $<)
EOF
INPUTS=(hello)
trials "$@"
