#!/bin/sh
# trs — shell wrapper that execs the native binary directly.
# Saves ~25ms vs the previous Node wrapper by skipping the node runtime.
#
# The platform-specific binary is installed by npm as an optionalDependency
# into node_modules/@dpeluche/trs-cli-<os>-<arch>/trs.

set -e

# Resolve real location of this script (npm installs it as a symlink).
SCRIPT="$0"
while [ -L "$SCRIPT" ]; do
  LINK=$(readlink "$SCRIPT")
  case "$LINK" in
    /*) SCRIPT="$LINK" ;;
    *) SCRIPT="$(dirname "$SCRIPT")/$LINK" ;;
  esac
done
DIR="$(cd "$(dirname "$SCRIPT")" && pwd)"
# DIR is .../node_modules/@dpeluche/trs/bin

OS=$(uname -s)
ARCH=$(uname -m)
case "$OS" in
  Darwin) OS=darwin ;;
  Linux) OS=linux ;;
  *) echo "trs: unsupported OS: $OS" >&2; exit 1 ;;
esac
case "$ARCH" in
  x86_64|amd64) ARCH=x64 ;;
  arm64|aarch64) ARCH=arm64 ;;
  *) echo "trs: unsupported arch: $ARCH" >&2; exit 1 ;;
esac

PKG="@dpeluche/trs-cli-$OS-$ARCH"
BIN=""

# Env override takes priority (custom builds / debugging)
if [ -n "${TRS_BINARY:-}" ] && [ -x "$TRS_BINARY" ]; then
  BIN="$TRS_BINARY"
fi

# Candidate locations npm may use for the optional dependency:
#  - sibling: hoisted to parent node_modules (npm local install, npm >=7)
#  - nested:  inside our own node_modules (npm install -g, pnpm isolated)
#  - parent:  deduplicated one level up (workspaces)
if [ -z "$BIN" ]; then
  for candidate in \
    "$DIR/../../trs-cli-$OS-$ARCH/trs" \
    "$DIR/../node_modules/$PKG/trs" \
    "$DIR/../../../$PKG/trs" \
    "$DIR/../../node_modules/$PKG/trs"; do
    if [ -x "$candidate" ]; then
      BIN="$candidate"
      break
    fi
  done
fi

if [ -z "$BIN" ]; then
  echo "trs: platform binary not found" >&2
  echo "" >&2
  echo "Expected package: $PKG" >&2
  echo "Searched near:    $DIR" >&2
  echo "" >&2
  echo "Alternatives:" >&2
  echo "  cargo install trs-cli    # build from source" >&2
  echo "  curl -fsSL https://usetrs.dev/install.sh | sh" >&2
  exit 1
fi

exec "$BIN" "$@"
