#!/bin/sh
arg=none

#Check if ISE_LIBRARY is defined, if not we use ISE_EIFFEL.
if [ -z "$ISE_LIBRARY" ]; then
	ISE_LIBRARY=$ISE_EIFFEL
	export ISE_LIBRARY
fi

#Use $MAKE as make utility instead of `make'.
if [ -z "$MAKE" ]; then
	make=make
else
	make=$MAKE
fi

if $make --version 2>/dev/null | grep GNU >/dev/null 2>&1; then
	case `uname` in
		Darwin) ncpus=`sysctl -n hw.activecpu` ;;
		Linux)
			if [ -f /proc/cpuinfo ] ; then
				ncpus=`grep -c '^processor[[:space:]]*:' /proc/cpuinfo`
			fi
			;;
		SunOS) ncpus=`/usr/sbin/psrinfo | wc -l` ;;
		IRIX*) ncpus=`hinv | awk '/^[0-9]+ [0-9]+ MHZ/ {print $1}'` ;;
	esac
	if [ -z "$MAKELEVEL" -a -n "$ncpus" ]; then
		if [ $ncpus -gt 1 ]; then
			make_args="-j $ncpus"
		fi
	fi
		# Special handling if `distcc' is currently used to speed up C compilation
		# time.
	if [ -n "$DISTCC_COUNT" ]; then
		make_args="-j $DISTCC_COUNT"
	fi
fi

if [ $# -gt 0 ]; then
	arg=$1
	if [ "$arg" != cecil -a "$arg" != "-cecil" -a "$arg" != "-library" -a "$arg" != "-silent" ]; then
		echo "Usage: finish_freezing [ -cecil | -library | -silent ]"
		exit 1
	fi
fi

if [ "$arg" != "-library" ]; then
	echo "Preparing C compilation ..."
	$ISE_EIFFEL/studio/spec/$ISE_PLATFORM/bin/quick_finalize . o
else
	echo "Generating C libraries ..."
fi

if [ ! -f config.sh ]; then
	cp $ISE_EIFFEL/studio/spec/$ISE_PLATFORM/include/config.sh .
fi
sh Makefile.SH

if [ "$arg"  = cecil -o "$arg" = "-cecil" ] ; then
	echo Generating CECIL library ...
	$make $make_args cecil && echo "C compilation completed"
else
	$make $make_args && echo "C compilation completed"
fi
