#!/bin/bash
wlfile=$1
length=${#wlfile}
pathwoextension=${wlfile:0:length-3}
filename=${pathwoextension##*/}
updated=false
set -e

echo "Compiling $wlfile to produce executable $filename"
stack build --nix :weblang

if [ ! -d intermediary ]; then
	mkdir intermediary
fi

if [ ! -f intermediary/$filename.ll ] || [ $wlfile -nt intermediary/$filename.ll ]; then
	stack exec weblang $wlfile intermediary/$filename.ll
	echo "intermediary/$filename.ll written"
	nix-shell -p llvm --command "llc intermediary/$filename.ll"
	echo "intermediary/$filename.s written"
	nix-shell -p gcc --command "g++ -c intermediary/$filename.s -o intermediary/$filename.o"
	echo "intermediary/$filename.o written"
	updated=true
else 
	echo "No updates to $wlfile since last compilation; not compiling this component"
fi

if [ ! -f jsonlib/jsonlib.o ] || [ jsonlib/jsonlib.cpp -nt jsonlib/jsonlib.o ]; then
	nix-shell -p rapidjson gcc --command "g++ \$NIX_CFLAGS_COMPILE -c jsonlib/jsonlib.cpp -o jsonlib/jsonlib.o"
	echo "jsonlib/jsonlib.o built"
	updated=true
else
	echo "No updates to jsonlib/jsonlib.cpp since last compilation; not compiling this component"
fi

if [ ! -f client/client.o ] || [ client/client.cpp -nt client/client.o ]; then
	nix-shell -p rapidjson gcc --command "gcc -Wall \$NIX_CFLAGS_COMPILE -c client/client.cpp -Iclient/cpr-example/opt/cpr/include -Iclient/cpr-example/opt/json/src -Lclient/cpr-example/build/lib -lcpr -lcurl -o client/client.o"
	echo "client/client.o built"
	updated=true
else
	echo "No updates to client/client.cpp since last compilation; not compiling this component"
fi

if [ ! -f $filename ] || [ $updated ]; then
        nix-shell -p curl gcc --command "g++ intermediary/$filename.o client/client.o jsonlib/jsonlib.o -o $filename -Lclient/cpr-example/build/lib -lcpr -lcurl"

	echo "Executable has been built: $filename"
else
	echo "No files were updated throughout the process and the executable $filename still exists; use that you bozo"
fi
