#!/usr/bin/env bash

mkdir -p dist

if [ -f dist/.compile-lock ]; then
	pid=$(cat dist/.compile-lock)
	ticks=0
	max_ticks=10

	if ! ps -p $pid > /dev/null; then
		echo "Detected a stale compile lock; deleting..."
		rm -f dist/.compile-lock
	else
		echo "Compilation already in progress; waiting up to $max_ticks seconds..."
	fi

	while [ -f dist/.compile-lock ]; do
		sleep 1
		let ticks=ticks+1

		if [ $ticks -ge $max_ticks ]; then
			echo "Timed out waiting for compilation to clear"
			exit 1
		fi
	done
fi

if [[ -f ./dist/.last-publish-time ]]; then
	echo "Found publication compile artifact; skipping recompilation."
	exit 3
fi

if [ -f dist/.last-compile-time ]; then
	if [ ! -d src ]; then
		# TODO: Confirm we're within a deploy environment
		echo "src folder does not exist; skipping recompilation."
		exit 3
	fi

	typeset -i last_modification_time=$(find src test -type f -print0 |
		xargs -0 stat -c "%X %N" |
		sort -rn |
		head -1 |
		awk '{ print $1 }')

	typeset -i last_compile_time=$(cat dist/.last-compile-time)

	if (( $last_compile_time > $last_modification_time )); then
		echo "No changes since last compile; skipping recompilation."
		exit 3
	fi
fi

# Compilation should occur.
exit 0
