#!/bin/sh
# agfile-rules.sh - generate make rules for AG files
# usage: agfile-rules.sh here|srcdir "syns" "output-extension" > rules.mk

if [ $# != 3 ]; then
    echo "$0: usage: $0 here|srcdir 'syns' 'output-extension'" 1>&2
    exit 1
fi

WHERE="$1"
SYNS="$2"
EXT="$3"

case "$WHERE" in
    here|srcdir) ;;
    *) echo "$0: deposit location must be either 'here' or 'srcdir'"
       exit 1
       ;;
esac

if [ "x$SYNS" = x ]; then
    echo 'agfiles agclean:;'
    exit 0
fi

for S in $SYNS; do
    echo $S | awk '
	{
	    syn=$1;
	    base=syn;
	    sub("\\.syn$", "", base);
	    cout=base ext;
	    hout=base ".h";

	    if (where == "srcdir") {
		dcout = "$(SRCDIR)/" cout;
		dhout = "$(SRCDIR)/" hout;
	    }
	    else {
		dcout = cout;
		dhout = hout;
	    }

	    printf "agfiles: %s %s\n", dcout, dhout;
	    printf "%s %s: $(SRCDIR)/%s\n", dcout, dhout, syn;
	    printf "\t@echo \"        [AGCL]    %-12s $(AGCLQUAL)\"\n", syn;

	    printf "\t@$(AGCL) $(SRCDIR)/%s\n", syn;
	    if (where == "srcdir") {
		printf "\t@mv %s %s\n", cout, dcout;
		printf "\t@mv %s %s\n", hout, dhout;
	    }
	}
    ' "ext=$EXT" "where=$WHERE"
done

echo $SYNS | tr ' ' '\n' | sed 's/.syn$//' | awk '
    BEGIN { printf "agclean:\n"; }
    {
	base = $1;
	if (where == "srcdir") {
	    base = "$(SRCDIR)/" base;
	}

	printf "\t@echo \"        [RM]      %s%s %s.h\"\n", base, ext, base;
	printf "\t@rm -f %s%s %s.h\n", base, ext, base;
    }
' "ext=$EXT" "where=$WHERE"

if [ $WHERE = here ]; then
    echo 'clean: agclean'
    echo 'beforeall: agfiles'
fi
