#!/bin/bash
#
# Usage:  ./test-cg.sh [-v] dir
#
#    where dir is the directory that contains the files to use.
#          [-v] is optinal flag to turn on verbose output
#
# Each test file must have a .expected file with the compiler
# output and the output when run.  Example:
#
#   Success.
#   3
#
# for a program that compiles and prints 3 when run.
#

VERBOSE="off"
if [ "$1" == "-v" ]; then
    VERBOSE="on"
    shift
fi

DIR=$1

PASSED=0
FAILED=0

# Iterate over all .ic files in DIR or its subdirectories
for f in `find $DIR -name "*.ic" `; do

    echo "$f"

    # Step 1: Run the Compiler, catching stdout and stderr

    if [ "$VERBOSE" = "on" ]; then
	echo "   Compiling $f ..."
    fi

    scala -classpath .:bin:tools/java-cup-11a.jar ic.Compiler $f > $f.output 2>&1

    # For now, just compare the last line of the output and first line of expected
    # The lines should be either "Success." or "Failed."  You can 
    # change these to have the script examine more of the output.
    EXPECT=`head -1 $f.expected`
    OUTPUT=`tail -1 $f.output`

    if [ "$OUTPUT" != "$EXPECT" ]; then
	echo "  Compilation Failed."

	let FAILED=FAILED+1

	echo "    Expected: $EXPECT"
	echo "    Got:      $OUTPUT"

	if [ "$VERBOSE" = "on" ]; then
   	    # Dump $f too, indenting each line with some spaces.
	    echo "    Code:"
	    cat $f | sed -e "s/^/        /g"
	    echo ""

	    # Dump full output
	    echo "    Full Output:"
	    cat $f.output | sed -e "s/^/        /g"

	    echo ""
	fi

    else if [ "$OUTPUT" != "Success." ]; then

	if [ "$VERBOSE" = "on" ]; then
	    echo "   Bad program --- skipping rest"
	fi

    else

	# Step 2: Compile the .s file
		
	if [ "$VERBOSE" = "on" ]; then
	    echo "   gcc ${BASE_NAME}.s ..."
	fi

	BASE_NAME="${f%.*}"
	gcc -m64 -g -o ${BASE_NAME}.exe ${BASE_NAME}.s libic64.a
	
	# Step 3: Run the binary

	if [ "$VERBOSE" = "on" ]; then
	    echo "   running ${BASE_NAME}.exe ..."
	fi 

	./${BASE_NAME}.exe > $f.result 2>&1
	
	# Compare output to expected output
	EXPECT=`tail -n +2 $f.expected`
	RESULT=`cat $f.result`
	
	# Report failure if we see the wrong result
	if [ "$EXPECT" != "$RESULT" ]; then
	    echo "  Test Run Failed."
	    
	    let FAILED=FAILED+1
	    
	    echo "    Expected: $EXPECT"
	    echo "    Got:      $RESULT"
	    
	    if [ "$VERBOSE" = "on" ]; then
   		# Dump $f too, indenting each line with some spaces.
		echo "    Code:"
		cat $f | sed -e "s/^/        /g"
		
		# Dump full output
		echo "    Full Result:"
		cat $f.result | sed -e "s/^/        /g"
		
		echo ""
	    fi
	else
	    let PASSED=PASSED+1
	fi
    fi
    fi
done

echo "# PASSED: $PASSED"
echo "# FAILED: $FAILED"

exit 0
