#!/bin/bash

mkdir -p bin

# Run sanity check.
./sanityCheck

HASH="$(git rev-list -n 1 --abbrev-commit HEAD)"

export TWEEGO_PATH=devTools/tweeGo/storyFormats
TWEEGO_EXE="tweego"

if hash $TWEEGO_EXE 2>/dev/null; then
	echo "system tweego binary"
else
	case "$(uname -m)" in
	x86_64|amd64)
		echo "x64 arch"
		if [ "$(uname -s)" = "Darwin" ]; then
			TWEEGO_EXE="./devTools/tweeGo/tweego_osx64"
		else
			TWEEGO_EXE="./devTools/tweeGo/tweego_nix64"
		fi
		;;
	x86|i[3-6]86)
		echo "x86 arch"
		if [ "$(uname -s)" = "Darwin" ]; then
			TWEEGO_EXE="./devTools/tweeGo/tweego_osx86"
		else
			TWEEGO_EXE="./devTools/tweeGo/tweego_nix86"
		fi
		;;
	*)
		echo "No system tweego binary found, and no precompiled binary for your platform available"
		echo "Please compile tweego and put the executable in PATH"
		exit 2
	esac
fi

$TWEEGO_EXE -o "bin/FC_pregmod_${HASH}_tmp.html" src/ --head devTools/head.html || build_failed="true"

#Make the output prettier, replacing \t with a tab and \n with a newline
sed -i -e '/^<div id="store-area".*$/s/\\t/\t/g' -e '/^<div id="store-area".*$/s/\\n/\n/g'  "bin/FC_pregmod_${HASH}_tmp.html" \
	&& mv "bin/FC_pregmod_${HASH}_tmp.html" "bin/FC_pregmod_${HASH}.html"

ln -s ../resources bin/ 2> /dev/null

echo "bin/FC_pregmod_$HASH.html compilation finished."