#!/usr/bin/env bash

if [[ $1 == '--help' ]]; then
	echo "Triggers recompilation of the source code for the current project."
	echo "Supported flags:"
	echo "--force : Bypasses any precompilation checks (cache, mutex, etc)"
	echo "          Use this if you want to recompile no matter what."
	echo " "
	exit 0
fi

if [[ $1 != '--force' ]]; then
	./bin/precompile

	case $? in
		1)
			exit 1
			;;
		3)
			exit 0
			;;
	esac
fi

echo "Recompiling..."
mkdir -p dist
echo $$ > dist/.compile-lock
rm -f dist/.last-compile-time

project_dir="$(dirname $(dirname "$0"))"

if [[ $1 == '--force' ]]; then
	rm -rf dist/src
	rm -rf dist/test
	./node_modules/.bin/tsc --declaration --project "$project_dir/config/tsconfig.json"
else
	./node_modules/.bin/tsc --declaration --incremental --project "$project_dir/config/tsconfig.json"
fi

exit_status=$?

if [[ $exit_status -eq 0 ]]; then
	./bin/remap-paths
	echo $(date +%s) > dist/.last-compile-time
fi

pid=$(cat dist/.compile-lock)

if [[ $pid == $$ ]]; then
	rm dist/.compile-lock
	exit $exit_status
else
	echo "Detected a conflicting compile lock..."
	exit 1
fi
