#!/bin/sh

# installation of fast ACK compilers afcc, afm2

# is the call correct?
case $# in
1)
	if [ -d $1 ] 
	then
		:
	else
		echo $0: $1 is not a directory >&2
		exit 1
	fi
	;;
*)
	echo $0: Call is $0 \<ACK home directory\> >&2
	exit 1
	;;
esac

# investigate machine: either vax or sun(3)

echo $0: determining type of machine ...
cat > t.c <<'EOF'
main() {
#ifdef sun
	printf("sun\n");
#endif
#ifdef vax
	printf("vax\n");
#endif
}
EOF
if cc t.c
then
	:
else
	echo $0: compilation failed >&2
	exit 1
fi
m=`./a.out`
rm -f a.out t.[co]
case $m in
sun|vax)
	echo $0: Starting installation for a $m ...
	;;
*)
	echo $0: machine must be sun or vax >&2
	exit 1
	;;
esac

# edit manual page
sed s@CHANGE_ME@$1/lib/m2@ < man/afm2.1.src > man/afm2.1

# install the compiler binaries

echo $0: copying compiler binaries ...
case $m in
sun)
	cp ack.sun/cemcom* ack.sun/m2* $1/lib/m68020
	;;
vax)
	cp ack.vax/cemcom* ack.vax/m2* $1/lib/vax4
	;;
esac

# now compile the driver program

echo $0: compiling driver program ...
rm -f afcc afm2
if cc -O -DACK_BIN -I$1/h -DFCC -o afcc driver.c &&
   cc -O -DACK_BIN -I$1/h -DFM2 -o afm2 driver.c
then
	:
else
	echo $0: compilation of driver program failed >&2
	exit 1
fi

( cd $1/lang/m2/libm2
  echo 'killbss() { }' > killbss.c
  ../../../bin/acc -L -c -LIB killbss.c
  cp LIST LIST.old
  echo 'killbss.c' >> LIST
  ../../../bin/arch r tail_m2.a killbss.c
) > /dev/null 2>&1

case $m in
sun)
	( cd $1/lib/sun3
	  cp tail_m2 tail_m2.orig
	  ../../bin/aal r tail_m2 ../../lang/m2/libm2/killbss.o
	)
	;;
vax)
	( cd $1/lib/vax4
	  cp tail_m2 tail_m2.orig
	  ar r tail_m2 ../../lang/m2/libm2/killbss.o
	  ranlib tail_m2
	)
	;;
esac > /dev/null 2>&1

#now run simple tests

echo $0: run some simple tests
failed=false
cat > test.mod <<'EOF'
MODULE test;
FROM InOut IMPORT	WriteString, WriteLn;
BEGIN
	WriteString("Hello World");
	WriteLn
END test.
EOF
if ./afm2 test.mod 2>/dev/null
then
	case `a.out` in
	"Hello World")
		;;
	*)
		echo $0: afm2 test failed >&2
		failed=true
		;;
	esac
else
	echo $0: afm2 compilation failed >&2
	failed=true
fi

cat > test.c <<'EOF'
main() { printf("Hello World\n"); }
EOF
if ./afcc test.c 2>/dev/null
then
	case `a.out` in
	"Hello World")
		;;
	*)
		echo $0: afcc test failed >&2
		failed=true
		;;
	esac
else
	echo $0: afcc compilation failed >&2
	failed=true
fi

rm -f test.* a.out

case $failed in
true)
	echo $0: some tests failed, installation aborted >&2
	exit 1
	;;
false)
	rm -f $1/bin/afm2 $1/bin/afcc
	cp afm2 afcc $1/bin
	rm -f afm2 afcc
	cp man/afcc.1 man/afm2.1 $1/man
	echo $0: Installation completed
	exit 0
	;;
esac
