#!/usr/bin/env bash
set -eu

WP_CI_BIN="$(dirname "${BASH_SOURCE[0]}")"
WP_CI="$WP_CI_BIN/.."
WP_ROOT="$WP_CI/.."

if [[ $# -gt 0 ]]; then
	shift
fi

run() {
	WP_CMD="${1-}"
	if [[ $# -gt 0 ]]; then
		shift
	fi

	case "$WP_CMD" in
		todo)
			run gir -m not_bound "$@"
			;;
		gir)
			exec "$WP_CI/gir.sh" "$@"
			;;
		fmt)
			exec cargo fmt -p wireplumber -p wp-examples "$@"
			;;
		sys)
			cd "$WP_ROOT/sys/generate"
			if [[ $# -eq 0 ]]; then
				set -- gir
			fi
			run "$@"
			;;
		gen|generate)
			cd "$WP_ROOT"
			exec nix run ${FLAKE_OPTS-} .#wpdev-generate -- "$@"
			;;
		install)
			WP_INSTALL="${1-}"
			if [[ $# -gt 0 ]]; then
				shift
			fi

			case "$WP_INSTALL" in
				gir)
					exec cargo install gir --root "$WP_CI" --git https://github.com/gtk-rs/gir --branch "$(jq -r '.nodes."gir-src".original.ref' flake.lock)" --rev "$(jq -r '.nodes."gir-src".locked.rev' flake.lock)" "$@"
					;;
				gir-files)
					GIR_FILES_CMD="${1-checkout}"
					if [[ $# -gt 0 ]]; then
						shift
					fi
					case "$GIR_FILES_CMD" in
						clone)
							exec git clone https://github.com/gtk-rs/gir-files "$WP_ROOT/gir-files" --branch "$(jq -r '.nodes."gir-files".original.ref' flake.lock)" "$@"
							;;
						checkout)
							GIR_FILES_NEEDS_CLONE=
							if [[ ! -e "$WP_ROOT/gir-files" ]] || rmdir "$WP_ROOT/gir-files" 2>/dev/null; then
								GIR_FILES_NEEDS_CLONE=1
							fi
							if [[ -n $GIR_FILES_NEEDS_CLONE ]]; then
								cargo wp install gir-files clone
							else
								git -C "$WP_ROOT/gir-files" fetch
							fi
							exec git -C "$WP_ROOT/gir-files" checkout --detach "$(jq -r '.nodes."gir-files".locked.rev' flake.lock)" "$@"
							;;
						pull)
							git -C "$WP_ROOT/gir-files" checkout "$(jq -r '.nodes."gir-files".original.ref' flake.lock)"
							exec git -C "$WP_ROOT/gir-files" pull "$@"
							;;
						*)
							echo expected gir-files subcommand: clone, checkout, pull
							return 1
							;;
					esac
					;;
				*)
					echo expected install target: gir, gir-files
					return 1
					;;
			esac
			;;
		*)
			echo expected subcommand: install, gir, sys, todo, fmt, commitlint
			return 1
			;;
	esac
}

run "$@"
