#!/bin/sh
# ./gcc.sh  -DALLEGRO_SRC -DALLEGRO_LIB_BUILD  -Wall -Wno-unused -Wno-long-double  -O2 -funroll-loops -ffast-math -fomit-frame-pointer -fno-common -pipe -dynamic -arch ppc -arch i386 -DALLEGRO_NO_ASM -I. -I./include -o obj/macosx/alleg/allegro.o -c src/allegro.c

origcmd=$@
arch_i386=0
arch_ppc=0
mode="link"
output=
cmd="gcc"

CFLAGS_i386=" -isysroot /Developer/SDKs/MacOSX10.4u.sdk"
LDFLAGS_i386=" -isysroot /Developer/SDKs/MacOSX10.4u.sdk -Wl,-syslibroot,/Developer/SDKs/MacOSX10.4u.sdk"

CFLAGS_PPC="  -isysroot /Developer/SDKs/MacOSX10.2.8.sdk"
LDFLAGS_PPC=" -isysroot /Developer/SDKs/MacOSX10.2.8.sdk -Wl,-syslibroot,/Developer/SDKs/MacOSX10.2.8.sdk"

while [ "$1" ]; do
	case $1 in
	-arch)
		shift
		if [ "$1" = "i386" ]; then
			if [ $arch_i386 -eq 1 ]; then
				echo Already specified i386
				exit 1
			fi
			arch_i386=1
		elif [ "$1" = "ppc" ]; then
			if [ $arch_ppc -eq 1 ]; then
				echo Already specified ppc
				exit 1
			fi
			arch_ppc=1
		else
			echo Unknown arch type $1
			exit 1
		fi
	;;

	-c)
		mode=compile
		cmd="$cmd -c"
	;;

	-o)
		shift
		output=$1
	;;

	*)
		cmd="$cmd $1"
	;;
	esac
	
	shift
done

# if both arch types aren't specified, the command can just be ran as is
if [ $arch_i386 -eq 0 ] || [ $arch_ppc -eq 0 ]; then
	gcc $origcmd
	exit $?
fi

# if no output, bail...
if [ "$output" = "" ]; then
	echo Error! $0 requires the -o switch.
	exit 1
fi

# figure out if we are compiling or linking
if [ "$mode" = "link" ]; then
	FLAGS_i386="$LDFLAGS_i386"
	FLAGS_PPC="$LDFLAGS_PPC"
elif [ "$mode" = "compile" ]; then
	FLAGS_i386="$CFLAGS_i386"
	FLAGS_PPC="$CFLAGS_PPC"
fi

# build the i386 version
$cmd $FLAGS_i386 -arch i386 -o $output.i386
if [ $? -ne 0 ]; then
	exit 1
fi

# build the PPC version
$cmd $FLAGS_PPC -arch ppc -o $output.ppc
if [ $? -ne 0 ]; then
	rm $output.i386
	exit 1 
fi

# create the universal version
lipo -create $output.i386 $output.ppc -output $output
if [ $? -ne 0 ]; then
	rm $output.i386 $output.ppc
	exit 1 
fi

# cleanup
rm $output.i386 $output.ppc
