#!/usr/bin/env bash
# Builds and runs Arena Tracker with the Windows Rust toolchain, from WSL (ADR-0003).
set -euo pipefail

cd "$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")/.."

usage() {
    echo "Usage : scripts/win <build|run> [arguments cargo...]" >&2
    exit 2
}

[ $# -ge 1 ] || usage
subcommand="$1"
shift
case "$subcommand" in
    build | run) ;;
    *) usage ;;
esac

if ! command -v cargo.exe >/dev/null 2>&1; then
    echo "Erreur : cargo.exe est introuvable. Installez Rust pour Windows (rustup) et vérifiez qu'il est dans le PATH de WSL." >&2
    exit 1
fi
if ! command -v cmd.exe >/dev/null 2>&1; then
    echo "Erreur : cmd.exe est introuvable. Vérifiez que les programmes Windows sont dans le PATH de WSL." >&2
    exit 1
fi

# The build directory lives on the Windows drive: %LOCALAPPDATA%\arena-tracker\target.
# cmd.exe is started from a Windows directory to avoid its warning about UNC paths.
windows_dir="$(dirname "$(command -v cmd.exe)")"
local_app_data="$(cd "$windows_dir" && cmd.exe /c 'echo %LOCALAPPDATA%' 2>/dev/null | tr -d '\r' || true)"
if [ -z "$local_app_data" ] || [ "$local_app_data" = '%LOCALAPPDATA%' ]; then
    echo "Erreur : impossible de déterminer %LOCALAPPDATA% via cmd.exe." >&2
    exit 1
fi
target_dir="${local_app_data}\\arena-tracker\\target"

# --locked: fail when Cargo.lock is stale instead of rewriting it (run `cargo test` in WSL to refresh it).
exec cargo.exe "$subcommand" --locked -p arena-tracker --target-dir "$target_dir" "$@"
