#!/bin/sh

set -eu

version=${ARENA_VERSION:-latest}
install_dir=${ARENA_INSTALL_DIR:-"$HOME/.local/bin"}
registry=${ARENA_REGISTRY:-https://registry.npmjs.org}
target_override=${ARENA_TARGET:-}
modify_path=true

usage() {
  cat <<'EOF'
Install the Arena single-file executable.

Usage:
  install.sh [--version VERSION] [--install-dir DIRECTORY] [--no-modify-path]

Environment variables:
  ARENA_VERSION          npm version or dist-tag (default: latest)
  ARENA_INSTALL_DIR      destination directory (default: ~/.local/bin)
  ARENA_REGISTRY         npm registry URL
  ARENA_TARGET           override detected target, for example linux-x64-musl
  ARENA_NO_MODIFY_PATH   set to 1 to avoid updating the shell profile
EOF
}

while [ "$#" -gt 0 ]; do
  case "$1" in
    --version)
      [ "$#" -ge 2 ] || { echo "--version requires a value" >&2; exit 2; }
      version=$2
      shift 2
      ;;
    --install-dir)
      [ "$#" -ge 2 ] || { echo "--install-dir requires a value" >&2; exit 2; }
      install_dir=$2
      shift 2
      ;;
    --no-modify-path)
      modify_path=false
      shift
      ;;
    -h|--help)
      usage
      exit 0
      ;;
    *)
      echo "unknown argument: $1" >&2
      usage >&2
      exit 2
      ;;
  esac
done

if [ "${ARENA_NO_MODIFY_PATH:-0}" = "1" ]; then
  modify_path=false
fi

command -v curl >/dev/null 2>&1 || {
  echo "Arena installer requires curl" >&2
  exit 1
}
command -v tar >/dev/null 2>&1 || {
  echo "Arena installer requires tar" >&2
  exit 1
}

detect_target() {
  os=$(uname -s)
  arch=$(uname -m)
  case "$arch" in
    x86_64|amd64) arch=x64 ;;
    arm64|aarch64) arch=arm64 ;;
    *) echo "Arena does not publish a binary for architecture $arch" >&2; exit 1 ;;
  esac

  case "$os" in
    Darwin)
      printf 'darwin-%s\n' "$arch"
      ;;
    Linux)
      libc=
      if [ -f /etc/alpine-release ]; then
        libc=musl
      elif command -v ldd >/dev/null 2>&1 && ldd --version 2>&1 | grep -qi musl; then
        libc=musl
      fi
      if [ "$libc" = musl ]; then
        printf 'linux-%s-musl\n' "$arch"
      else
        printf 'linux-%s\n' "$arch"
      fi
      ;;
    *)
      echo "Arena install.sh supports macOS and Linux, not $os" >&2
      exit 1
      ;;
  esac
}

target=${target_override:-$(detect_target)}
case "$target" in
  darwin-arm64|darwin-x64|linux-arm64|linux-arm64-musl|linux-x64|linux-x64-musl)
    ;;
  *)
    echo "Arena does not publish an install.sh binary for $target" >&2
    exit 1
    ;;
esac

package_name="@qwen-code/arena-$target"
encoded_package=$(printf '%s' "$package_name" | sed 's|/|%2f|g')
metadata_url="${registry%/}/${encoded_package}/${version}"

echo "Resolving $package_name@$version"
metadata=$(curl -fsSL "$metadata_url") || {
  echo "Could not resolve $package_name@$version from $registry" >&2
  exit 1
}
metadata=$(printf '%s' "$metadata" | tr -d '\n')
resolved_version=$(printf '%s' "$metadata" | sed -n 's/.*"version":"\([^"]*\)".*/\1/p')
tarball_url=$(printf '%s' "$metadata" | sed -n 's/.*"tarball":"\([^"]*\)".*/\1/p')
expected_shasum=$(printf '%s' "$metadata" | sed -n 's/.*"shasum":"\([0-9a-f]*\)".*/\1/p')

if [ -z "$resolved_version" ] || [ -z "$tarball_url" ]; then
  echo "npm returned incomplete metadata for $package_name@$version" >&2
  exit 1
fi

tmp_dir=$(mktemp -d "${TMPDIR:-/tmp}/arena-install.XXXXXX")
install_tmp=
cleanup() {
  rm -rf "$tmp_dir"
  if [ -n "$install_tmp" ]; then rm -f "$install_tmp"; fi
}
trap cleanup EXIT HUP INT TERM

archive="$tmp_dir/arena.tgz"
curl -fsSL "$tarball_url" -o "$archive"

if [ -n "$expected_shasum" ]; then
  actual_shasum=
  if command -v sha1sum >/dev/null 2>&1; then
    actual_shasum=$(sha1sum "$archive" | awk '{print $1}')
  elif command -v shasum >/dev/null 2>&1; then
    actual_shasum=$(shasum -a 1 "$archive" | awk '{print $1}')
  fi
  if [ -n "$actual_shasum" ] && [ "$actual_shasum" != "$expected_shasum" ]; then
    echo "Downloaded Arena archive failed its checksum" >&2
    exit 1
  fi
fi

tar -xzf "$archive" -C "$tmp_dir"
source_binary="$tmp_dir/package/bin/arena"
if [ ! -f "$source_binary" ]; then
  echo "Arena archive does not contain package/bin/arena" >&2
  exit 1
fi

mkdir -p "$install_dir"
install_tmp="$install_dir/.arena.$$"
cp "$source_binary" "$install_tmp"
chmod 755 "$install_tmp"

case "$target" in
  darwin-*)
    if command -v codesign >/dev/null 2>&1 && ! codesign --verify "$install_tmp" >/dev/null 2>&1; then
      codesign --force --sign - "$install_tmp" >/dev/null
    fi
    ;;
esac

mv -f "$install_tmp" "$install_dir/arena"
install_tmp=

"$install_dir/arena" --version

case ":$PATH:" in
  *":$install_dir:"*) ;;
  *)
    if [ "$modify_path" = true ]; then
      shell_name=$(basename "${SHELL:-sh}")
      case "$shell_name" in
        zsh) profile=${ZDOTDIR:-$HOME}/.zshrc ;;
        bash) profile=$HOME/.bashrc ;;
        *) profile=$HOME/.profile ;;
      esac
      path_line="export PATH=\"$install_dir:\$PATH\""
      if [ ! -f "$profile" ] || ! grep -F "$path_line" "$profile" >/dev/null 2>&1; then
        printf '\n# Arena CLI\n%s\n' "$path_line" >> "$profile"
      fi
      echo "Added $install_dir to PATH in $profile"
    else
      echo "Add $install_dir to PATH to run arena without its full path."
    fi
    ;;
esac

echo "Arena $resolved_version installed at $install_dir/arena"
