#!/usr/bin/env sh
#
# benchwright install — pipe to sh:
#   curl -fsSL https://benchwright.ai/install.sh | sh
#
# Detects (os, arch), pulls the matching binary from the
# cli-binaries Supabase bucket, verifies sha256 against the
# released checksums.txt, and drops it on PATH. No root unless
# /usr/local/bin is the only writable bindir.
#
# Tunables (env vars):
#   BW_VERSION    pin a specific release, e.g. BW_VERSION=v0.1.2 sh install.sh
#                 default: latest
#   BW_INSTALL_DIR  override install destination (default picks the first
#                   writable: $HOME/.local/bin → /usr/local/bin)
#   BW_API_URL    override the API URL written into a fresh config; defaults
#                 to whichever instance hosted this script. Useful when
#                 piping `curl … | BW_API_URL=https://staging.foo.bar/v1 sh`
#   BW_NO_VERIFY  skip checksum verification (NOT recommended)
#   BW_NO_CONFIG  skip config-seeding (don't write ~/.config/benchwright/…)

set -eu

BASE="https://huaidexxitdaclprytnp.supabase.co/storage/v1/object/public/cli-binaries"
DEFAULT_API_URL="https://benchwright.ai"
VERSION="${BW_VERSION:-latest}"
case "$VERSION" in
    latest|v*|[0-9]*) ;;
    *) echo "install: BW_VERSION must be 'latest' or vX.Y.Z (got: $VERSION)" >&2; exit 1 ;;
esac
# Normalise pin URLs: if the user passed "0.1.2" make it "v0.1.2"
case "$VERSION" in
    [0-9]*) VERSION="v${VERSION}" ;;
esac

# ── (1) detect platform ────────────────────────────────────────
# `uname -s` returns Linux/Darwin/MINGW*/CYGWIN*. We don't ship a
# Windows .sh installer (use scoop/PowerShell on Windows), so
# anything outside linux/darwin errors out with a clear message.
uname_s="$(uname -s 2>/dev/null || echo unknown)"
case "$uname_s" in
    Linux)   os="linux" ;;
    Darwin)  os="darwin" ;;
    *)
        echo "install: unsupported OS '$uname_s' (this script handles linux + darwin)" >&2
        echo "for windows, grab a binary from $BASE/$VERSION/" >&2
        exit 1
        ;;
esac

uname_m="$(uname -m 2>/dev/null || echo unknown)"
case "$uname_m" in
    x86_64|amd64)        arch="amd64" ;;
    aarch64|arm64)       arch="arm64" ;;
    *)
        echo "install: unsupported arch '$uname_m'" >&2
        exit 1
        ;;
esac

asset="benchwright-${os}-${arch}"
url="${BASE}/${VERSION}/${asset}"
checksums_url="${BASE}/${VERSION}/checksums.txt"

# ── (2) pick the install dir ──────────────────────────────────
# Prefer a per-user dir we know we can write without sudo. Fall
# back to /usr/local/bin via sudo if nothing in PATH is writable.
pick_dir() {
    if [ -n "${BW_INSTALL_DIR:-}" ]; then
        printf '%s\n' "$BW_INSTALL_DIR"
        return
    fi
    for d in "$HOME/.local/bin" "$HOME/bin"; do
        if [ -w "$d" ] || mkdir -p "$d" 2>/dev/null && [ -w "$d" ]; then
            printf '%s\n' "$d"
            return
        fi
    done
    printf '%s\n' "/usr/local/bin"
}
install_dir="$(pick_dir)"
# `mkdir -p` first so the writability probe doesn't trip when the
# user passed an explicit BW_INSTALL_DIR that doesn't exist yet —
# `[ -w nonexistent ]` returns false, which would force a needless
# sudo. Fail-soft: ignore mkdir failure (it might be /usr/local/bin
# which we can't create as user but can write to via sudo below).
mkdir -p "$install_dir" 2>/dev/null || true
need_sudo=0
if [ ! -w "$install_dir" ]; then
    need_sudo=1
fi

# ── (3) download to a tmp dir + verify ────────────────────────
tmp="$(mktemp -d 2>/dev/null || mktemp -d -t benchwright)"
trap 'rm -rf "$tmp"' EXIT INT TERM

echo "→ benchwright (${VERSION}, ${os}/${arch})"
echo "  $url"

dl() {
    # curl is the priority; wget covers Alpine etc.
    if command -v curl >/dev/null 2>&1; then
        curl -fSL --retry 3 --retry-delay 2 -o "$2" "$1"
    elif command -v wget >/dev/null 2>&1; then
        wget -qO "$2" "$1"
    else
        echo "install: need curl or wget" >&2
        exit 1
    fi
}

dl "$url" "$tmp/$asset"

if [ "${BW_NO_VERIFY:-}" != "1" ]; then
    if dl "$checksums_url" "$tmp/checksums.txt" 2>/dev/null; then
        # Pull just the line for our binary; awk avoids piping the
        # whole file through `shasum -c` (which expects exact path
        # matches and trips on `./benchwright-linux-amd64` vs
        # `benchwright-linux-amd64`).
        expected="$(awk -v a="$asset" '$2 ~ a { print $1; exit }' "$tmp/checksums.txt")"
        if [ -z "$expected" ]; then
            echo "  (checksum: not listed in checksums.txt — skipping)"
        else
            if command -v sha256sum >/dev/null 2>&1; then
                actual="$(sha256sum "$tmp/$asset" | awk '{print $1}')"
            elif command -v shasum >/dev/null 2>&1; then
                actual="$(shasum -a 256 "$tmp/$asset" | awk '{print $1}')"
            else
                echo "  (checksum: no sha256sum/shasum on PATH — skipping)"
                actual="$expected"
            fi
            if [ "$actual" != "$expected" ]; then
                echo "install: checksum mismatch" >&2
                echo "  expected: $expected" >&2
                echo "  actual:   $actual" >&2
                exit 1
            fi
            echo "  ✓ sha256 verified"
        fi
    else
        echo "  (checksum file not available — skipping)"
    fi
fi

chmod +x "$tmp/$asset"

# ── (4) move into place ───────────────────────────────────────
dest="$install_dir/benchwright"
if [ "$need_sudo" = "1" ]; then
    echo "  installing to $dest (sudo)"
    sudo mv "$tmp/$asset" "$dest"
else
    echo "  installing to $dest"
    mv "$tmp/$asset" "$dest"
fi

# ── (5) PATH sanity check ─────────────────────────────────────
case ":$PATH:" in
    *":$install_dir:"*) on_path=1 ;;
    *) on_path=0 ;;
esac

echo
"$dest" version || true
echo
if [ "$on_path" = "0" ]; then
    echo "note: $install_dir is not on your PATH. Add it to your shell rc:"
    echo "    export PATH=\"$install_dir:\$PATH\""
fi

# ── (6) seed a config so `benchwright login` doesn't have to be told
#       --api-url every time. We only write the file when it's
#       missing — never clobber an existing PAT/profile. The user can
#       still override per-call with `BW_API_URL` or
#       `--api-url`.
api_url="${BW_API_URL:-$DEFAULT_API_URL}"
if [ -n "$api_url" ] && [ "${BW_NO_CONFIG:-0}" != "1" ]; then
    cfg_dir="${XDG_CONFIG_HOME:-$HOME/.config}/benchwright"
    cfg_file="$cfg_dir/config.toml"
    if [ ! -f "$cfg_file" ]; then
        mkdir -p "$cfg_dir" 2>/dev/null || true
        umask 077
        cat > "$cfg_file" <<EOF
default_profile = "default"

[profile.default]
api_url = "$api_url"
EOF
        chmod 600 "$cfg_file" 2>/dev/null || true
        echo "  seeded $cfg_file (api_url = $api_url)"
    fi
fi

if [ -n "$api_url" ]; then
    echo "next: benchwright login          # PAT will be saved against $api_url"
else
    echo "next: benchwright login --api-url <your-api-url>"
fi
