#!/bin/sh
# testsubdir-rules.sh - generate make rules for testsubdir.mk
# usage: testsubdir-rules.sh "subdirs" > rules.mk

if [ $# != 1 ]; then
    echo "$0: usage: $0 'subdirs'" 1>&2
    exit 1
fi

SUBDIRS="$1"

echo "$SUBDIRS" | tr ' ' '\n' | awk '
    { dirs[++ndirs] = $1; }
    END {
	printf "all:\n";
	for (i=1;i<=ndirs;i++) dodir("run-tests", 1, dirs[i]);
	for (i=1;i<=ndirs;i++) dodir("show-diffs", 1, dirs[i]);
	simpletarget("show-diffs", "", 0);
	simpletarget("run-tests", "", 1);
	simpletarget("rules", "-subdirs", 1);
	simpletarget("clean", "-subdirs", 1);
	simpletarget("distclean", "-subdirs", 1);
    }
    function simpletarget(target, suffix, show) {
	printf "%s%s:\n", target, suffix;
	for (i=1;i<=ndirs;i++) dodir(target, show, dirs[i]);
    }
    function dodir(target, show, dir) {
	if (show) {
	    printf "\t@echo \"%s ===> $(_SUBDIR_)%s\"\n", target, dir;
	}
	printf "\t@cd %s && $(MAKE) %s", dir, target;
	printf " _SUBDIR_=$(_SUBDIR_)%s/\n", dir;
    }
'

echo ".PHONY: all run-tests show-diffs"
echo ".PHONY: rules-subdirs clean-subdirs distclean-subdirs"

echo 'distclean-here:'
for D in $SUBDIRS; do
    echo $D | awk '
	{
	    printf "\t@echo \"        [RMDIR]   %s\"\n", $1;
	    printf "\t@-rm -f %s/Makefile %s/rules.mk %s/depend.mk\n",$1,$1,$1;
	    printf "\t@-rmdir %s\n", $1;
	}
    '
done
