# !/bin/sh

VMLANG="vmlang"
VMASM="vmasm"
VMLINK="vmlink"
DD="dd"
MKTEMP="mktemp"
RM="rm"

ENTRY_POINT="init"
OBJ_FILE="file.vo"
EXEC_FILE="file.v"
INC_FOLDER="."
CFLAG=0
OFLAG=0

build_exec()
{
	if [ $OFLAG != 0 ] ; then
		EXEC_FILE=$OUT_FILE
	fi
	
	for FILE in $FILES
	do
		HEADER=$($DD bs=3 count=1 if=$FILE 2>/dev/null)
	
		if [ "$HEADER" != ".VM" ] ; then
			ASM_NAME=$($MKTEMP)
			$VMLANG -o $ASM_NAME -I $INC_FOLDER $FILE
			if [ $? != 0 ] ; then
				$RM $ASM_NAME > /dev/null 2>&1
				exit 1		
			fi
		
			OBJ_NAME=$($MKTEMP)
			$VMASM -o $OBJ_NAME $ASM_NAME
			if [ $? != 0 ] ; then
				$RM $ASM_NAME > /dev/null 2>&1
				$RM $OBJ_NAME > /dev/null 2>&1
				exit 1		
			fi
		
			$RM $ASM_NAME > /dev/null 2>&1
			BUILD="$BUILD $OBJ_NAME"
		else
			OBJ="$OBJ $FILE"		
		fi	 
	done

	$VMLINK -e $ENTRY_POINT -o $EXEC_FILE $OBJ $BUILD
	if [ $? != 0 ] ; then
		$RM $BUILD > /dev/null 2>&1
		exit 1
	fi
	
	$RM $BUILD > /dev/null 2>&1
}

build_obj()
{
	if [ $OFLAG != 0 ] ; then
		OBJ_FILE=$OUT_FILE
	fi
	
	ASM_NAME=$($MKTEMP)
	$VMLANG -o $ASM_NAME $FILES
	if [ $? != 0 ] ; then
		$RM $ASM_NAME > /dev/null 2>&1
		exit 1		
	fi
	
	$VMASM -o $OBJ_FILE $ASM_NAME
	if [ $? != 0 ] ; then
		$RM $ASM_NAME > /dev/null 2>&1
		$RM $OBJ_FILE > /dev/null 2>&1
		exit 1
	fi
	
	$RM $ASM_NAME > /dev/null 2>&1
}

show_help()
{
	echo Description: simple wrapper for vm tools
	echo
	echo Usage: vmc [options] in_file...
	echo " -c		Compile and assemble, but do not link"
	echo " -o <file>	Place the output into <file>"
	echo " -e <name>	Symbol name of entry point" 
	echo " -I <folder>	Folder with include files" 
	echo
}

while getopts ":ce:o:I:" Option

do
  case $Option in
    c)
    	CFLAG=1
    ;;
    o)
    	OFLAG=1
    	OUT_FILE=$OPTARG
    ;;
    
    e)  # $OPTARG
    	ENTRY_POINT=$OPTARG
    ;;
    I)
	INC_FLAG=1
	INC_FOLDER=$OPTARG	
    ;;
    *)
    show_help
    exit 1
    ;;
  esac
done

shift $(($OPTIND - 1))

if [ "$#" == 0 ] ; then
	show_help
	exit 1
fi

FILES="$*"

if [ "$CFLAG" != 0 ] ; then
	if [ "$#" != 1 ] ; then
		echo cannot specify -c with multiple files
		exit 1
	fi
	build_obj
else
	build_exec	
fi

exit 0
