#!/bin/bash
#compile all the files if they ends with .fk

txtund=$(tput sgr  1)          # Underline
txtbld=$(tput bold)             # Bold
bldred=${txtbld}$(tput setaf 1) #  red
bldblu=${txtbld}$(tput setaf 4) #  blue
bldwht=${txtbld}$(tput setaf 6) #  white
txtrst=$(tput sgr0)             # Reset
info=${bldwht}*${txtrst}        # Feedback
pass=${bldblu}*${txtrst}
warn=${bldred}*${txtrst}
ques=${bldblu}?${txtrst}


STOP_ON_ERROR=true
COMPILER="./fk2c"

if [ -e "./fk2c.d.byte" ]; then
	COMPILER="./fk2c.d.byte"
fi
STOP=false
CHECK_TYPE_only=false

function compile {
	echo "$info COMPILING $1 $info" 
	$COMPILER $1 > "_funk/$2.c" && echo "$pass Ocaml to C of $1 succeeded $pass" && $CHECK_TYPE_only && astyle "_funk/$2.c" && return
	$CHECK_TYPE_only && STOP=true && echo "$warn Ocaml to C of $1 failed $warn" && return
	gcc -Wall -g -I../src/frontend/../backend/c/include -L../src/frontend/../backend/c -o "_funk/$2" "_funk/$2.c" -lbackend -lpthread  && echo "$pass COMPILATION of $1 succeeded $pass" && return
	echo "$warn C to binary of $1 failed $warn"
	STOP=true
}

if [ -e "_funk" ]; then
	rm -rf "_funk"
fi

mkdir -p "_funk"


if [ $# -lt 1 ]; then
echo "usage ./compile [-dt] files"
exit -1
fi


while getopts ":dt" opt; do
	case $opt in
		d)
			STOP_ON_ERROR=false
			shift
			;;
		t)
			CHECK_TYPE_only=true
			shift
			;;
	esac
done	


echo "Compiling all the files ends with .fk"

if [ $# -gt 1 ]; then
make
fi

for file in $@
do
filename=$(basename "$file")
extension="${filename##*.}"
filename="${filename%.*}"

	if [ "$extension" == "fk" ];
	then	
		compile $file $filename
		if  $STOP_ON_ERROR && $STOP; then
			exit -1
		fi
	fi
done
echo "$info All test passed $info"
exit
