#!/bin/sh

set -e

create_dir $CONFIG

create_dir $CONFIG/bin
echo "#!/bin/sh" > $CONFIG/bin/ack_sys
echo "echo $SYSNAME" >> $CONFIG/bin/ack_sys
chmod +x $CONFIG/bin/ack_sys

cd $SRC_HOME
find . -type d -perm -555 -print > $CONFIG/dir_list

cd $CONFIG
for i in mach/*/libsys
do
	rm -rf $i
done

for i in `cat dir_list`
do
	create_dir $i
	rm -f $i/No*
	if [ -f $i/Makefile ]
	then
		( cd $i ; if make clean ; then exit 0 ; else exit 0 ; fi ) > /dev/null 2>&1 
	fi
	if [ -f $SRC_HOME/$i/proto.make ]
	then mk_makefile $SRC_HOME/$i/proto.make > $i/Makefile
	fi
	if [ -f $SRC_HOME/$i/Action ]
	then
		cd $SRC_HOME/$i
		cp Action* $CONFIG/$i
		chmod +w $CONFIG/$i/Action*
		cd $CONFIG
	fi
done

cd $CONFIG

for i in lang/cem/cemcom.ansi lang/cem/cemcom lang/m2/comp
do
	cp $SRC_HOME/$i/BigPars $CONFIG/$i/Parameters
	chmod +w $CONFIG/$i/Parameters
done
for i in lang/pc/comp lang/cem/cpp.ansi
do
	cp $SRC_HOME/$i/Parameters $CONFIG/$i/Parameters
	chmod +w $CONFIG/$i/Parameters
done

cd $CONFIG/mach
for i in *
do
    if [ -d $i ]
    then
	if [ -d $i/as ]
	then
		cd $i/as
		mk_makefile $SRC_HOME/mach/proto/as/proto.make | sed -e "/#MACH_DEFINE/,/^MACH/s/=.*/= $i/" > Makefile
		cd ../..
	fi
	if [ -d $i/top ]
	then
		cd $i/top
		mk_makefile $SRC_HOME/mach/proto/top/proto.make | sed -e "/#MACH_DEFINE/,/^MACH/s/=.*/= $i/" > Makefile
		cd ../..
	fi
	if [ -d $i/cg ]
	then
		cd $i/cg
		mk_makefile $SRC_HOME/mach/proto/cg/proto.make | sed -e "/#MACH_DEFINE/,/^MACH/s/=.*/= $i/" > Makefile
		cd ../..
	fi
	if [ -d $i/ncg ]
	then
		cd $i/ncg
		mk_makefile $SRC_HOME/mach/proto/ncg/proto.make | sed -e "/#MACH_DEFINE/,/^MACH/s/=.*/= $i/" > Makefile
		if [ -f $SRC_HOME/mach/$i/ncg/table_dir ]
		then
			ed -s Makefile <<EOF
/^#TABLE_DEFINE/+1r $SRC_HOME/mach/$i/ncg/table_dir
w
q
EOF
		fi
		cd ../..
	fi
	if [ -f $SRC_HOME/mach/$i/mach_params ]
	then	:
	else	continue
	fi
	for j in libem libend libmon libfp libsys libdb
	do
	    if [ -d $i/$j ]
	    then
		cd $i/$j
		mk_makefile $SRC_HOME/mach/proto/libg/proto.$j | sed -e "/#MACH_PARAMS/r $SRC_HOME/mach/$i/mach_params" > Makefile
		cd ../..
	    fi
	done
	for j in libbsd4_1a libbsd4_2 libsysV_2
	do
	    if [ -d $i/$j ]
	    then
		cd $i/$j
		mk_makefile $SRC_HOME/mach/proto/libg/proto.libsys | sed -e "/#MACH_PARAMS/r $SRC_HOME/mach/$i/mach_params" -e "s/libsys/$j/g" > Makefile
		cd ../..
	    fi
	done
	for j in libcc libcc.ansi libm2 libpc libbc liboc libf77
	do
	    create_dir $i/$j
	    rm -f $i/$j/No*
	    cd $i/$j
	    mk_makefile $SRC_HOME/mach/proto/libg/proto.$j | sed -e "/#MACH_PARAMS/r $SRC_HOME/mach/$i/mach_params" > Makefile
	    cd ../..
	done
	if [ $i = vax4 ]
	then :
	elif [ -d $i/libsys ]
	then :
	else 
		create_dir $i/libsys
		rm -f $i/libsys/No*
		cd $i/libsys
		mk_makefile $SRC_HOME/mach/proto/libg/proto.sysmon | sed -e "/#MACH_PARAMS/r $SRC_HOME/mach/$i/mach_params" > Makefile
		cd ../..
	fi
    fi
done
