#!/bin/sh
# tools/fv/fv - Flying V build wrapper.
# The public Agila source now uses the .fv extension, but the underlying V
# compiler only accepts .v files. This wrapper stages temporary .v copies of
# every .fv file in the project, invokes tools/v/v, and then removes the copies.
set -eu

ROOT=$(CDPATH= cd -- "$(dirname -- "$0")/../.." && pwd)
V_CMD="./tools/v/v"

stage_all_fv() {
	# Copy every .fv source to a sibling .v, except inside the V compiler tree.
	find "$ROOT" -name '*.fv' -not -path '*/tools/v/*' -print0 \
		| while IFS= read -r -d '' fv; do
			cp "$fv" "${fv%.fv}.v"
		done
}

cleanup() {
	# Remove any temporary .v files we created, but never touch the V compiler.
	find "$ROOT" -name '*.v' -not -path '*/tools/v/*' -delete
}

trap cleanup EXIT INT TERM

stage_all_fv

# Rewrite arguments from .fv to .v and make them relative to ROOT so the V
# compiler does not have to deal with the space in the parent directory name.
new_args=""
for arg in "$@"; do
	rel="$arg"
	case "$arg" in
		"$ROOT"/*) rel="${arg#$ROOT/}" ;;
		"$ROOT")   rel="." ;;
	esac
	case "$rel" in
		*.fv) new_args="$new_args ${rel%.fv}.v" ;;
		*)    new_args="$new_args $rel" ;;
	esac
done

cd "$ROOT"
"$V_CMD" $new_args
