#!/bin/bash
# Called with [input program] [output program]

if [ $# -ne 2 ]
then
    echo "usage: $0 <input file> <output program>"
    exit 1
fi

# Check if libsdl2-dev is installed
dpkg-query -l libsdl2-dev > /dev/null
if [ "$?" -ne "0" ]
then
    echo "Warning: dpkg/libsdl2-dev not installed! Compilation may fail!"
fi

cat $1 | ./preprocessor > temp.seami
cat temp.seami | ./seam > gen.c
if [ "$?" -ne "0" ] 
then
    echo "Error encountered while compiling: "
    cat gen.c

    rm temp.seami
    rm gen.c
    exit 1
else
    echo "Input program translated succesfully; compiling..."
fi

# See Google: http://superuser.com/questions/246837/how-do-i-add-text-to-the-beginning-of-a-file-in-bash
echo "#include \"gen.h\"" | cat - gen.c > temp && mv temp gen.c
echo "#include \"lib.h\"" | cat - gen.c > temp && mv temp gen.c

echo " void program_ep() { World_spawn(); }" >> gen.c

gcc -g -c lib.c -o lib.o
gcc -g -c gen.c -o gen.o
gcc -g -c main.c -o main.o
gcc -g main.o lib.o gen.o -lSDL2  -o $2

if [ "$?" -ne "0" ]
then
	echo "Compilation error! Checkout temp.seami and gen.c."
else
	rm temp.seami
	rm gen.c
	echo "$2 created."
fi
