#!/usr/bin/env sh
set -e

REPO="yuval-a/snippets"
BIN_NAME="snippets"
INSTALL_DIR_DEFAULT="$HOME/.local/bin"

# allow overrides
if [ -n "$SNIPPETS_REPO" ]; then REPO="$SNIPPETS_REPO"; fi
if [ -n "$SNIPPETS_BIN" ]; then BIN_NAME="$SNIPPETS_BIN"; fi

need_cmd() { command -v "$1" >/dev/null 2>&1 || { echo "error: '$1' is required" >&2; exit 1; }; }
need_cmd curl

OS=$(uname -s | tr '[:upper:]' '[:lower:]')
ARCH=$(uname -m | tr '[:upper:]' '[:lower:]')
case "$OS" in
  linux)
    SUFFIX="linux.tar.gz"
    ;;
  darwin)
    case "$ARCH" in
      arm64|aarch64) SUFFIX="macos-aarch64.tar.gz" ;;
      x86_64|amd64)  SUFFIX="macos-x86_64.tar.gz" ;;
      *) SUFFIX="macos.tar.gz" ;;
    esac
    ;;
  msys*|mingw*|cygwin*) echo "Use install.ps1 on Windows" >&2; exit 1;;
  *) echo "Unsupported OS: $(uname -s)" >&2; exit 1;;
esac

API_URL="https://api.github.com/repos/$REPO/releases/latest"
echo "Detecting latest release from $REPO…" >&2

# fetch latest JSON and locate asset URL
JSON=$(curl -fsSL "$API_URL")
ASSET_URL=$(printf "%s" "$JSON" | grep -Eo '"browser_download_url"\s*:\s*"[^"]+' | cut -d'"' -f4 | grep "$SUFFIX" | head -n1)
if [ -z "$ASSET_URL" ] && [ "$OS" = "darwin" ]; then
  # Fallback to generic macOS archive name if arch-specific is not found (older releases)
  ASSET_URL=$(printf "%s" "$JSON" | grep -Eo '"browser_download_url"\s*:\s*"[^"]+' | cut -d'"' -f4 | grep "macos.tar.gz" | head -n1)
fi
if [ -z "$ASSET_URL" ]; then
  echo "warning: no prebuilt asset found for '$SUFFIX'" >&2
  if command -v cargo >/dev/null 2>&1; then
    echo "Falling back to 'cargo install --git https://github.com/$REPO.git'" >&2
    cargo install --git "https://github.com/$REPO.git" "$BIN_NAME"
    echo "Installed via cargo. Ensure ~/.cargo/bin is on PATH." >&2
    exit 0
  else
    echo "error: Rust toolchain not found (cargo missing) and no prebuilt asset is available." >&2
    echo "       Install Rust from https://rustup.rs or use Homebrew: brew install --HEAD https://raw.githubusercontent.com/yuval-a/snippets/main/Formula/snippets.rb" >&2
    exit 1
  fi
fi

CHECKSUM_URL="${ASSET_URL}.sha256"

TMPDIR=${TMPDIR:-"/tmp"}
ARCHIVE="$TMPDIR/$BIN_NAME-archive.tgz"
SUMFILE="$ARCHIVE.sha256"

echo "Downloading: $ASSET_URL" >&2
curl -fsSL "$ASSET_URL" -o "$ARCHIVE"

echo "Downloading checksum: $CHECKSUM_URL" >&2
if curl -fsSL "$CHECKSUM_URL" -o "$SUMFILE"; then
  echo "Verifying checksum…" >&2
  if command -v shasum >/dev/null 2>&1; then
    EXPECTED=$(cut -d' ' -f1 "$SUMFILE")
    ACTUAL=$(shasum -a 256 "$ARCHIVE" | awk '{print $1}')
    [ "$EXPECTED" = "$ACTUAL" ] || { echo "error: checksum mismatch" >&2; exit 1; }
  elif command -v sha256sum >/dev/null 2>&1; then
    (cd "$(dirname "$ARCHIVE")" && sha256sum -c "$(basename "$SUMFILE")") || { echo "error: checksum mismatch" >&2; exit 1; }
  else
    echo "warning: no shasum/sha256sum; skipping verification" >&2
  fi
else
  echo "warning: checksum not available; skipping verification" >&2
fi

WORK="$TMPDIR/$BIN_NAME-install-$$"
mkdir -p "$WORK"
tar -xzf "$ARCHIVE" -C "$WORK"

# Locate extracted binary
BIN_PATH=""
if [ -f "$WORK/$BIN_NAME" ]; then BIN_PATH="$WORK/$BIN_NAME"; fi
if [ -z "$BIN_PATH" ]; then
  # try find
  BIN_PATH=$(find "$WORK" -type f -name "$BIN_NAME" -perm +111 2>/dev/null | head -n1)
fi
if [ -z "$BIN_PATH" ]; then
  echo "error: could not find '$BIN_NAME' in archive" >&2
  exit 1
fi

# Choose install dir
INSTALL_DIR="$INSTALL_DIR_DEFAULT"
if [ -w /usr/local/bin ]; then INSTALL_DIR="/usr/local/bin"; fi
mkdir -p "$INSTALL_DIR"
install -m 0755 "$BIN_PATH" "$INSTALL_DIR/$BIN_NAME"
echo "Installed: $INSTALL_DIR/$BIN_NAME" >&2

case :$PATH: in
  *:$INSTALL_DIR:*) ;;
  *) echo "note: $INSTALL_DIR is not on PATH; add it or move the binary." >&2 ;;
esac

echo "Done." >&2
