#!/bin/sh

set -eu
# e: Exit on untested errors
# x: Print all commands to stdout before executing.
# u: Error if reading expanding unset variables

trap "echo \"*** At least one test has failed!\"; exit 1" EXIT

echo "*** Cleaning up ..."
make clean

echo "*** Removing foo.c ..."
rm -f foo.c

echo "*** Running make (should fail) ..."
if make all; then exit 1; fi

echo "*** Generating foo.c ..."
cat << EOF > foo.c
#include "foo.h"
#include "generated.h"
EOF

echo "*** Running make again (should pass) ..."
make all
foo_o_mtime=`stat --format=%Y foo.o`
bar_o_mtime=`stat --format=%Y bar.o`
generated_h_mtime=`stat --format=%Y generated.h`

# avoid problems with low time resolution
sleep 1

echo "*** Touching \"foo.h\", this should cause \"foo.o\" and \"bar.o\" to be rebuilt ..."
touch foo.h
make all
foo_o_mtime_new=`stat --format=%Y foo.o`
bar_o_mtime_new=`stat --format=%Y bar.o`
[ $foo_o_mtime_new -gt $foo_o_mtime ]
[ $bar_o_mtime_new -gt $bar_o_mtime ]
foo_o_mtime=$foo_o_mtime_new
bar_o_mtime=$bar_o_mtime_new

# avoid problems with low time resolution
sleep 1

echo "*** Touching \"generated.x\", this should cause \"generated.h\" and \"foo.o\" (but not \"bar.o\") to be rebuilt ..."
touch generated.x
make all
generated_h_mtime_new=`stat --format=%Y generated.h`
foo_o_mtime_new=`stat --format=%Y foo.o`
bar_o_mtime_new=`stat --format=%Y bar.o`
[ $generated_h_mtime_new -gt $generated_h_mtime ]
[ $foo_o_mtime_new -gt $foo_o_mtime ]
[ $bar_o_mtime_new -eq $bar_o_mtime ]

echo "*** Removing foo.c ..."
rm -f foo.c

echo "*** Running make (should fail) ..."
if make all; then exit 1; fi

echo ""
echo "*** All tests have been successful!"

trap - EXIT

exit 0
