#!/bin/sh
#Generator make files for refal project

help(){
  echo "Generator of make file for refal project"
  echo "usage `basename $0` [options] [file-list]"
  echo "options are:"
  echo "   -o <name> Name of executable file"
  echo "   -m <name> Name of makefile"
  echo "   -q Be quiet"
  echo "   -h Get this help"
  exit 0;
}

case "$#" in
   "0") help;;
    *) ;;
esac

makefile="./makefile"

bin=`dirname $0`
cur=`pwd`
cd $bin/..
REFAL_HOME=`pwd`
cd $cur

while :
do
case "$1" in
   -o) shift;TARGET=$1;;
   -m) shift;makefile=$1;; 
   -h) help;;
   -q) quiet=yes;;
   -*) echo "Ignoing $1";;
   *) break;;
esac
shift;
done
files=$*

> $makefile
case "$?" in
   "0") ;;
    *) echo "Can't create file " $makefile;;
esac

echo "REFAL_HOME=$REFAL_HOME" >> $makefile
cat >> $makefile <<'EOF'
# Generated automatically. Fri Sep 24 14:58:44 1999
REFAL_LIB=$(REFAL_HOME)/lib
REFAL_BIN=$(REFAL_HOME)/bin
CC=gcc
RLINK=$(REFAL_BIN)/rmod2c
RCOMP=$(REFAL_BIN)/rcomp
CFLAGS=
SLIB=$(REFAL_LIB)/rlib.a $(REFAL_LIB)/rlib2.a
ILIB=$(REFAL_LIB)/ri.o $(SLIB)
TLIB=$(REFAL_LIB)/rit.o $(REFAL_LIB)/trace.a $(SLIB)

.SUFFIXES: .ref .mod
EOF


for i in $files
do
  case $i in
      *.ref) ext=ref;;
      *.mod) ext=mod;;
      *.c)   ext=c;;
      *.o)   ext=o;;
      *.a)   ext=a;;
      *)     echo "Unknown extension " $i ". Skipped.";continue;;
  esac
  base=`basename $i .$ext`
  fdir=`dirname $i`
  [ "$TARGET" = "" ] && TARGET=$base
  case $ext in
     mod) MOD="$MOD $i";;
     ref)gen=$fdir/$base.mod; 
         MOD="$MOD $gen";
         [ "$fdir" != "$cur" ] && DEPS=$DEPS"\n$gen: $i" 
         RM=$RM" $gen"
         ;;
     c)  gen=$base.o;
         [ "$fdir" != "$cur" ] && DEPS=$DEPS"\n$gen: $i" 
         RM=$RM" $gen"
         EOBJ="$EOBJ $gen";;
     o)  EOBJ="$EOBJ $i";;
     a)  EOBJ="$EOBJ $i";;
  esac
done
RM=$RM" $TARGET $TARGET.c $TARGET.o"
echo "TARGET=$TARGET" >> $makefile
echo "MOD=$MOD" >> $makefile
echo "EOBJ=$EOBJ" >> $makefile
echo "RM=$RM" >> $makefile
cat >> $makefile <<'EOF'
all: $(TARGET)

$(TARGET): $(TARGET).o $(ILIB) $(EOBJ)
	$(CC) -o $(TARGET) $(TARGET).o $(ILIB) $(EOBJ)

debug: $(TARGET).o $(TLIB) $(EOBJ)
	$(CC) -o $(TARGET) $(TARGET).o $(TLIB) $(EOBJ)

clean:
	rm -f $(RM)
$(TARGET).c: $(MOD)
	$(RLINK) -o $(TARGET).c $(MOD)

.ref.mod .SILENT:
	rm -f .mod
	-$(RCOMP) $<
	-test -f .mod -a ! -f $*.mod  &&  mv .mod $*.mod

.c.o:
	$(CC) $(CFLAGS) $(CLOCAL) -c $<
EOF
echo $DEPS >> $makefile
