#!/bin/sh
set -eu

REPO="sachaos/shuire"
BIN="shuire"
INSTALL_DIR="${INSTALL_DIR:-${HOME}/.local/bin}"

# Detect OS
OS_RAW="$(uname -s)"
case "$OS_RAW" in
  Darwin) OS="macos" ;;
  Linux)  OS="linux" ;;
  *)
    echo "Unsupported OS: ${OS_RAW}" >&2
    exit 1
    ;;
esac

# Detect architecture
ARCH_RAW="$(uname -m)"
case "$ARCH_RAW" in
  x86_64)          ARCH="x86_64" ;;
  arm64 | aarch64) ARCH="arm64"  ;;
  *)
    echo "Unsupported architecture: ${ARCH_RAW}" >&2
    exit 1
    ;;
esac

# Resolve version
if [ -z "${VERSION:-}" ]; then
  API_RESPONSE=$(curl -fsSL "https://api.github.com/repos/${REPO}/releases/latest")
  if command -v jq > /dev/null 2>&1; then
    VERSION=$(printf '%s' "$API_RESPONSE" | jq -r '.tag_name')
  else
    VERSION=$(printf '%s' "$API_RESPONSE" \
      | grep '"tag_name"' | sed 's/.*"tag_name": *"\([^"]*\)".*/\1/')
  fi
  if [ -z "$VERSION" ]; then
    echo "Failed to resolve latest version from GitHub API" >&2
    exit 1
  fi
fi

TARBALL="${BIN}-${VERSION}-${OS}-${ARCH}.tar.gz"
URL="https://github.com/${REPO}/releases/download/${VERSION}/${TARBALL}"

echo "Installing ${BIN} ${VERSION} (${OS}/${ARCH}) → ${INSTALL_DIR}"

TMP=$(mktemp -d)
trap 'rm -rf "$TMP"' EXIT

curl -fsSL "$URL" -o "${TMP}/${TARBALL}"
tar -xzf "${TMP}/${TARBALL}" -C "$TMP"

if [ ! -f "${TMP}/${BIN}" ]; then
  echo "Binary '${BIN}' not found in downloaded tarball" >&2
  exit 1
fi

mkdir -p "$INSTALL_DIR"
mv "${TMP}/${BIN}" "${INSTALL_DIR}/${BIN}"
chmod +x "${INSTALL_DIR}/${BIN}"

echo "Done. Make sure ${INSTALL_DIR} is in your PATH."
echo "  ${BIN} --version"
