#!/bin/bash
OS="10.6"
ARCH="32"
ARCHPRT=""
showopts () {
  echo "
	Usage: 
        compile filename osver architecture
           * fname=asmfile with no extension, .asm will be added.
           * tosver=Mac OS X Version: 10.6 or 10.7 [default 10.6]
           * architecture= 32 or 64 (bits) [default 32]
"
  exit
}
file="./$1.asm"
if [ -z $1 ]; then
	echo ""
	echo "Error: No Input File Specified."
	showopts
fi
if [ ! -e $file ]; then
	echo ""
    echo "Error: File $1.asm not found in the current directory."
	showopts
fi
if [ -z $2 ]; then
	OS="10.6"
else
	if [ $2 != "10.6" ] && [ $2 != "10.7" ]; then
		echo ""
    	echo "    Error: Unknown OS version. Please use 10.6 for Snow Leopard or 10.7 for Lion."
		showopts
	fi
fi
if [ -z $3 ]; then
	ARCH="i386"
	ARCHPRT="32"
else
	if [ $3 != "32" ] && [ $3 != "64" ]; then
		echo ""
    	echo "    Error: No architecture specified, please specify 32 or 64 bits."
		showopts
	else 
		ARCHPRT=$3
		if [ $3 == "32" ]; then
			ARCH="i386"
		else
			if [ $3 == "64" ]; then
				ARCH="x86_64"
			fi
		fi
	fi
fi
echo "
*** Compiling with FASM...
"
./fasm $1.asm $1.o
echo "
*** Converting to Match-O $ARCHPRT bits object format..."
./objconv -fmacho$ARCHPRT -nu $1.o $1_m.o
echo "
*** Linking...
"
ld -arch $ARCH -macosx_version_min $OS -o $1 $1_m.o /usr/lib/crt1.o /usr/lib/libc.dylib

#gcc -m$ARCHPRT -o $1 $1_m.o

echo "
*** DONE.
"