#!/bin/sh
# script/yarn: run yarn with the given arguments under the node
# script/bootstrap would use. Every script that runs yarn on the host
# runs it through this one, except script/bootstrap, which picks its
# own node and yarn.
set -eu

ROOT="$(cd "$(dirname "$0")/.." && pwd -P)"

# Must match the pins in script/bootstrap.
NODE_VERSION="22.17.0"
NODE_MIN_VERSION="22.13.0"

# node_ok: the node on PATH has the major version of NODE_VERSION and is
# at least NODE_MIN_VERSION. Only the major is compared with the pin,
# as REPO_POLICIES.md asks. node itself compares the versions: major,
# then minor, then patch. A node that fails does not pass.
# script/bootstrap and script/yarn carry this function unchanged.
node_ok() {
    if ! command -v node >/dev/null 2>&1; then return 1; fi
    node -e '
        const have = process.versions.node.split(".").map(Number);
        const want = process.argv[1].split(".").map(Number);
        const pinned = process.argv[2].split(".").map(Number);
        if (have[0] !== pinned[0]) process.exit(1);
        for (let i = 0; i < 3; i++) {
            if (have[i] !== want[i]) process.exit(have[i] > want[i] ? 0 : 1);
        }
    ' "$NODE_MIN_VERSION" "$NODE_VERSION"
}

# Run the yarn script/bootstrap installed: the yarn on PATH when the
# node on PATH passes node_ok, and otherwise yarn under the pinned node
# in nvm. nvm is a bash script, hence the subshell.
run_yarn() {
    if node_ok && command -v yarn >/dev/null 2>&1; then
        exec yarn "$@"
    fi
    if node_ok || [ ! -s "$HOME/.nvm/nvm.sh" ]; then
        echo "script/yarn: no yarn; run script/bootstrap first" >&2
        exit 1
    fi
    exec bash -c '. "$HOME/.nvm/nvm.sh" && nvm use "$1" >/dev/null &&
        shift && exec yarn "$@"' bash "$NODE_VERSION" "$@"
}

main() {
    cd "$ROOT"
    # script/bootstrap links the node and yarn it installs into
    # ~/.local/bin, which the shell that called it may not have on PATH.
    PATH="$HOME/.local/bin:$PATH"
    run_yarn "$@"
}

main "$@"
