#!/usr/bin/bash

set -euo pipefail

cd "$(dirname "${BASH_SOURCE[0]}")"

COMMON_DIR="$(realpath common)"
export COMMON_DIR

OUTDIR=$(mktemp --directory)
trap "rm -rf '$OUTDIR'" EXIT

run_solution() {
	local solution=$1
	local input=$2

	if [[ -d "$solution" ]]; then
		if [[ -f "$solution/Cargo.toml" ]]; then
			cargo run --quiet --manifest-path "$solution/Cargo.toml" < "$input"
		else
			runfile=$solution/run.sh
			[[ -f "$runfile" ]] || { echo "Error: $runfile not found" >&2; exit 1; }
			"$runfile" "$input"
		fi
	else
		case "$(basename "$solution")" in
			*.hs)
				runhaskell -icommon "$solution" < "$input"
				;;
			*.py)
				python "$solution" < "$input"
				;;
			*)
				echo "Error: Unknown solution type: $solution" >&2
				exit 1
				;;
		esac
	fi
}

do_day() {
	local year=$1
	local day=$2

	local input=$year/data/day$day.input
	local expected=$year/data/day$day.expected

	for solution in "$year/day$day"/*; do
		echo -n "$solution... "

		case "${solution##*/}" in
			example*)
				echo SKIP
				continue
				;;
			*)
				;;
		esac

		local solution_output=$OUTDIR/${year}_$day.out
		run_solution "$solution" "$input" > "$solution_output"

		if ! diff -u "$expected" "$solution_output"; then
			echo FAIL
			rv=$?
			case "$rv" in
				1)
					exit 2
					;;
				*)
					exit 1
					;;
			esac
		else
			echo ok
		fi
	done
}

do_year() {
	local year=$1

	for day in $(seq 1 25); do
		do_day "$year" "$day"
	done
}

shopt -s dotglob nullglob

for year in 2020 2021 2022; do
	do_year "$year"
done
