#!/bin/sh

# installation of fast ACK compilers fcc, fm2, and fpc

# 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 \<bin 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
	$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

# make links to proper bin and lib directories

echo $0: creating bin and lib directories ...
rm -f bin lib
ln -s bin.$m bin
ln -s lib.$m lib

# edit manual page
sed s@CHANGE_ME@`pwd`/def@ < man/fm2.1.src > man/fm2.1

# now compile the driver program

echo $0: compiling driver program ...
rm -f fcc fm2 fpc
SunOs4=
if [ -f /usr/lib/ld.so ]
then
# different options for the loader on SunOs 4.0
	SunOs4=-DSunOs4
fi
if cc -O -DFASTDIR=\"`pwd`\" $SunOs4 -DFCC -o fcc driver.c &&
   cc -O -DFASTDIR=\"`pwd`\" $SunOs4 -DFM2 -o fm2 driver.c &&
   cc -O -DFASTDIR=\"`pwd`\" $SunOs4 -DFPC -o fpc driver.c
then
	:
else
	echo $0: compilation of driver program failed >&2
	exit 1
fi

if cc -o str_change str_change.c
then
	case $m in
	vax)
		./str_change CHANGE_ME `pwd` < bin.vax/m2mm > fm2mm
		;;
	sun)
		./str_change CHANGE_ME `pwd` < bin.sun/m2mm > fm2mm
		;;
	esac
	rm -f str_change.o str_change
	chmod +x fm2mm
else
	echo "$0: compilation of string patching program failed; cannot create fm2mm" >&2
fi

#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 ./fm2 test.mod 2>/dev/null
then
	case `a.out` in
	"Hello World")
		;;
	*)
		echo $0: fm2 test failed >&2
		failed=true
		;;
	esac
else
	echo $0: fm2 compilation failed >&2
	failed=true
fi

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

cat > test.p <<'EOF'
program p(output); begin writeln('Hello World') end.
EOF
if ./fpc test.p 2>/dev/null
then
	case `a.out` in
	"Hello World")
		;;
	*)
		echo $0: fpc test failed >&2
		failed=true
		;;
	esac
else
	echo $0: fpc 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/fm2 $1/fcc $1/fpc
	cp fm2 fcc fpc $1
	if [ -f fm2mm ]
	then
		rm -f $1/fm2mm
		cp fm2mm $1/fm2mm
	fi
	rm -f fm2 fpc fcc fm2mm
	echo $0: Installation completed
	exit 0
	;;
esac