#!/bin/sh
# agfile-rules.sh - generate make rules for AG files
# usage:
#    agfile-rules.sh where syns ext maint > rules.mk
#

if [ $# != 4 ]; then
    echo "$0: usage: $0 where syns ext maint" 1>&2
    echo "    where:      here | srcdir" 1>&2
    echo "    syns:       list of .syn files" 1>&2
    echo "    ext:        output extension, e.g. '.c'" 1>&2
    echo "    maint:      maintainer | nonmaintainer" 1>&2
    exit 1
fi

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

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

echo 'agforce: ;'
echo 'DOAGFORCE='
echo 'DOAGFORCE0='
echo 'DOAGFORCE1=agforce'

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

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

	    if (maint == "maintainer") {
	        tool = " $(AGCL)";
	    }
	    else {
		tool = "";
	    }

	    force = "$(DOAGFORCE$(AGFORCE))"

	    printf "agfiles: %s %s\n", dcout, dhout;
	    printf "%s %s: %s %s %s\n", dcout, dhout, synsrc, tool, force;
	    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" "maint=$MAINT"
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
