#!/usr/bin/env bash
# tuningfork inside WSL, from a checkout on Windows, from Git Bash:
#
#   scripts/tuningfork <command> [args]         any tuningfork command, as on Linux
#   scripts/tuningfork --run <program> [args]   anything else, in tuningfork's venv
#
# The checkout stays where Windows editors see it; tuningfork's venv and its recordings stay
# in the distro's Linux file system, where SQLite's locking works. tuningfork.ps1 is its twin
# for PowerShell: change both together.
#
# It runs nothing until TUNINGFORK_WSL_DISTRO names the distro: with more than one installed,
# the default one may not be the one meant. Each argument reaches tuningfork as it was typed.
set -euo pipefail

if [ -z "${TUNINGFORK_WSL_DISTRO:-}" ]; then
    echo 'Name the WSL distro tuningfork runs in first, for example:  export TUNINGFORK_WSL_DISTRO=Ubuntu' >&2
    echo 'The distros installed here:' >&2
    WSL_UTF8=1 wsl.exe --list --verbose >&2
    exit 2
fi

here="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
repo="$(cygpath -w "$here" 2>/dev/null || printf '%s' "$here")"

# Run in the distro: one fixed script, the arguments after it, never read back as shell.
script='export UV_PROJECT_ENVIRONMENT="$HOME/.local/share/tuningfork/venv"; '\
'command -v uv >/dev/null || { echo "uv is not installed in this distro: curl -LsSf https://astral.sh/uv/install.sh | sh" >&2; exit 127; }; '\
'if [ "${1:-}" = --run ]; then shift; exec uv run "$@"; fi; exec uv run tuningfork "$@"'

# Git Bash rewrites an argument that looks like a POSIX path into a Windows one: /tmp/lab
# would reach the distro as C:/Program Files/Git/tmp/lab.
export MSYS_NO_PATHCONV=1 MSYS2_ARG_CONV_EXCL='*'
WSL_UTF8=1 exec wsl.exe --distribution "$TUNINGFORK_WSL_DISTRO" --cd "$repo" --exec bash -lc "$script" tuningfork "$@"
