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

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

TARGETS="$1"
SUBDIRS="$2"
MORESUBDIRS="$3"

# Remove anything from MORESUBDIRS that's already in DIRS
MORESUBDIRS=`(echo 1 $SUBDIRS; echo 2 $MORESUBDIRS) | awk '
    /^1 / { for (i=2;i<=NF;i++) seen[$i] = 1; }
    /^2 / { for (i=2;i<=NF;i++) if (!seen[$i]) print $i; }
'`

for T in $TARGETS; do
    if [ "$T" != rules -a "$T" != distclean ]; then
	echo "${T}: ${T}-subdirs"
    fi
done

for T in $TARGETS; do
    echo "${T}-subdirs:"

    if [ "$T" = rules -o "$T" = distclean ]; then
	DIRS="$SUBDIRS $MORESUBDIRS"
    else
	DIRS="$SUBDIRS"
    fi

    for D in $DIRS; do
	echo $D | awk '{
	    printf "\t@echo \"%s ===> $(_SUBDIR_)%s\"\n", t, $1;
	    printf "\t@cd %s && $(MAKE) %s _SUBDIR_=$(_SUBDIR_)%s/\n", $1,t,$1;
	}' "t=$T"
    done
done

for T in $TARGETS; do
    echo ".PHONY: $T ${T}-subdirs"
done

echo 'distclean-here:'
for D in $SUBDIRS $MORESUBDIRS; 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
