#!/bin/sh
COMPILER='/usr/pkg/bin/gcc-mp-4.4'
SUFFIX='\.c'
OUTPUT_O='NO'
OUTPUT=''
NAMED_OUTPUT=''
LASTFILE=''
INTEL='YES'
SIZE32='NO'
SIZE64='NO'
NEWARGS=''

SKIP='NO'

for arg in $@
do
	if [ $SKIP = 'ARCH' ]; then
		# intercept -arch option and set SIZEXX
		SKIP='NO'
		if [ $arg = 'x86_64' ] || [ $arg = 'ppc64' ]; then
			SIZE64='YES'
		else
			SIZE32='YES'
		fi
		
		# which architecture are we compiling for?
		if [ $arg = 'ppc64' ] || [ $arg = 'ppc' ]; then
			INTEL='NO'
		fi
		
	elif [ $arg = '-arch' ]; then
		SKIP='ARCH'
	
	else
		NEWARGS+="$arg "
		
		# if the -c option is given, the output is .o
		if [ $arg = '-c' ]; then
			OUTPUT_O='YES'
		fi

		# if the output file is given by a -o option, record it
		if [ $SKIP = 'O' ]; then
			SKIP='NO'
			NAMED_OUTPUT=$arg
		fi
		
		if [ $arg = '-o' ]; then
			SKIP='O'
		fi
		
		# note each file ending by ${SUFFIX}
		# transform it in .o and remember the last one
		if `echo $arg | grep -q "${SUFFIX}$"`; then
			LASTFILE=$arg
			OUTPUT+=`echo $arg | sed "s/${SUFFIX}/\.o/"`
			OUTPUT+=' '
		fi
	fi
done

# What is the output?

if [ ${NAMED_OUTPUT}"X" != "X" ]; then
	OUTPUT=$NAMED_OUTPUT

elif [ $OUTPUT_O = 'NO' ]; then
	# It is an executable whose is name is the LASTFILE without suffix
	OUTPUT=`echo ${LASTFILE} | sed "s/${SUFFIX}//"`
fi

# Othewise, the output is just the ${OUTPUT} variable as computed before
# Now, compile

if [ $SIZE32 = 'YES' ] && [ $SIZE64 = 'NO' ]; then
	if `${COMPILER} -m32 $NEWARGS`; then
		exit 0
	else
		exit 1
	fi
	
elif [ $SIZE32 = 'NO' ] && [ $SIZE64 = 'YES' ]; then
	if `${COMPILER} -m64 $NEWARGS`; then
		exit 0
	else
		exit 1
	fi

else
	# Universal case
	if `${COMPILER} -m32 $NEWARGS`; then
		for filename in ${OUTPUT}
		do
			mv ${OUTPUT} ${OUTPUT}.32
		done
	
		if `${COMPILER} -m64 $NEWARGS`; then
			for filename in ${OUTPUT}
			do
				mv ${OUTPUT} ${OUTPUT}.64
				if [ $INTEL = 'YES' ]; then
					lipo -create -arch x86_64 ${OUTPUT}.64 \
						 -arch i386 ${OUTPUT}.32 \
			 			 -output ${OUTPUT}
				else
					lipo -create -arch ppc64 ${OUTPUT}.64 \
						 -arch ppc ${OUTPUT}.32 \
			 			 -output ${OUTPUT}
				fi
			
				rm -f ${OUTPUT}.32 ${OUTPUT}.64
			done
		else
			exit 1
		fi
	else
		exit 1
	fi
fi
exit 0