#!/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

# Default path: sibling package in node_modules/@dpeluche/
BIN="$DIR/../../trs-cli-$OS-$ARCH/trs"

# Env override for custom builds / debugging
if [ -n "${TRS_BINARY:-}" ]; then
  BIN="$TRS_BINARY"
fi

if [ ! -x "$BIN" ]; then
  echo "trs: binary not found at $BIN" >&2
  echo "" >&2
  echo "Expected platform package: @dpeluche/trs-cli-$OS-$ARCH" >&2
  echo "" >&2
  echo "Alternatives:" >&2
  echo "  cargo install tars-cli    # build from source" >&2
  echo "  brew install trs          # macOS (when available)" >&2
  exit 1
fi

exec "$BIN" "$@"
