#!/bin/sh

count=$(( `find -name '*.[cS]' | wc -l` + 1 ))

while true; do
    name=`find -name '*.[cS]' | head -n $((RANDOM % count)) | tail -1`
    # empty name is not ok
    test "$name" || continue
    # name starting with ./extra/ is not ok
    test "${name##./extra/*}" || continue
    # name starting with ./scripts/ is not ok
    test "${name##./scripts/*}" || continue
    # this is not ok too
    test "$name" = "./lib/interp.c" && continue
    # don't try to build if it has no corresponding object file
    name_b="$name"
    name_b="${name_b%.c}"
    name_b="${name_b%.S}"
    name_o="${name_b}.o"
    name_os="${name_b}.os"
    name_oS="${name_b}.oS"
    test ! -e "$name_o" && test ! -e "$name_os" && test ! -e "$name_oS" && continue
    # touch, and run make to rebuild object file(s)
    echo "Touching $name"
    touch "$name"
    echo "Running make (should rebuild it):"
    out=`./z_test0 2>&1`
    test "$out" || { echo "ERROR! No output!"; exit 1; }
    echo "$out"
    echo "Running make again (should not build anything):"
    out=`./z_test0 2>&1`
    test "$out" && echo "$out"
    test "$out" && { echo "ERROR! Produced some output!"; exit 1; }
    echo "End of make runs"
done
