#!/usr/bin/env sh
# buildline installer
# Downloads the prebuilt binary for your platform from the latest GitHub release.
# Usage: curl -fsSL https://github.com/nabsei/buildline/releases/latest/download/install.sh | sh
#
# To install to a custom directory:
#   curl -fsSL .../install.sh | INSTALL_DIR=~/.local/bin sh

set -e

REPO="nabsei/buildline"
INSTALL_DIR="${INSTALL_DIR:-/usr/local/bin}"

# ── detect OS ────────────────────────────────────────────────────────────────
os="$(uname -s)"
case "$os" in
  Linux)  os_name="linux" ;;
  Darwin) os_name="macos" ;;
  *)
    echo "error: unsupported OS: $os" >&2
    echo "Install manually from https://github.com/$REPO/releases" >&2
    exit 1
    ;;
esac

# ── detect architecture ───────────────────────────────────────────────────────
arch="$(uname -m)"
case "$arch" in
  x86_64 | amd64) arch_name="x86_64" ;;
  arm64 | aarch64)
    if [ "$os_name" = "macos" ]; then
      arch_name="aarch64"
    else
      echo "error: no prebuilt binary for Linux arm64 yet." >&2
      echo "Install via cargo: cargo install buildline" >&2
      exit 1
    fi
    ;;
  *)
    echo "error: unsupported architecture: $arch" >&2
    echo "Install via cargo: cargo install buildline" >&2
    exit 1
    ;;
esac

# ── resolve target triple ─────────────────────────────────────────────────────
case "${os_name}-${arch_name}" in
  linux-x86_64)   target="x86_64-unknown-linux-gnu" ;  ext="tar.gz" ;;
  macos-x86_64)   target="x86_64-apple-darwin"      ;  ext="tar.gz" ;;
  macos-aarch64)  target="aarch64-apple-darwin"      ;  ext="tar.gz" ;;
esac

archive="buildline-${target}.${ext}"
url="https://github.com/${REPO}/releases/latest/download/${archive}"

# ── download & install ────────────────────────────────────────────────────────
tmp="$(mktemp -d)"
trap 'rm -rf "$tmp"' EXIT

echo "Downloading $archive ..."
if command -v curl >/dev/null 2>&1; then
  curl -fsSL "$url" -o "$tmp/$archive"
elif command -v wget >/dev/null 2>&1; then
  wget -q "$url" -O "$tmp/$archive"
else
  echo "error: neither curl nor wget found." >&2
  exit 1
fi

echo "Extracting ..."
tar -xzf "$tmp/$archive" -C "$tmp"

echo "Installing to $INSTALL_DIR ..."
if [ -w "$INSTALL_DIR" ]; then
  mv "$tmp/buildline" "$INSTALL_DIR/buildline"
else
  sudo mv "$tmp/buildline" "$INSTALL_DIR/buildline"
fi

chmod +x "$INSTALL_DIR/buildline"

echo ""
echo "buildline installed successfully!"
echo "Run: buildline demo"
