#!/usr/bin/env sh
# Install the latest release of ralph from GitHub.
#
# Usage:
#   curl -fsSL https://raw.githubusercontent.com/akkeshavan/ralph/main/install.sh | sh
#
# Options (env vars):
#   RALPH_VERSION  — pin a specific version, e.g. RALPH_VERSION=v0.2.0 ... | sh
#   RALPH_INSTALL  — installation directory (default: /usr/local/bin, fallback: ~/.local/bin)

set -e

REPO="akkeshavan/ralph"
BINARY="ralph"

# ── Detect OS ──────────────────────────────────────────────────────────────────
OS="$(uname -s)"
ARCH="$(uname -m)"

case "$OS" in
  Linux)
    case "$ARCH" in
      x86_64)  TARGET="x86_64-unknown-linux-gnu" ;;
      aarch64|arm64) TARGET="aarch64-unknown-linux-gnu" ;;
      *)
        echo "Unsupported Linux architecture: $ARCH" >&2
        exit 1
        ;;
    esac
    EXT="tar.gz"
    ;;
  Darwin)
    case "$ARCH" in
      x86_64)  TARGET="x86_64-apple-darwin" ;;
      arm64)   TARGET="aarch64-apple-darwin" ;;
      *)
        echo "Unsupported macOS architecture: $ARCH" >&2
        exit 1
        ;;
    esac
    EXT="tar.gz"
    ;;
  *)
    echo "Unsupported OS: $OS" >&2
    echo "For Windows, download manually from: https://github.com/${REPO}/releases" >&2
    exit 1
    ;;
esac

# ── Resolve version ────────────────────────────────────────────────────────────
if [ -z "$RALPH_VERSION" ]; then
  echo "Fetching latest version..."
  RALPH_VERSION="$(curl -fsSL "https://api.github.com/repos/${REPO}/releases/latest" \
    | grep '"tag_name"' \
    | sed 's/.*"tag_name": *"\(.*\)".*/\1/')"
  if [ -z "$RALPH_VERSION" ]; then
    echo "Could not determine latest version. Set RALPH_VERSION manually." >&2
    exit 1
  fi
fi

echo "Installing ralph ${RALPH_VERSION} (${TARGET})..."

# ── Download ───────────────────────────────────────────────────────────────────
ASSET="${BINARY}-${RALPH_VERSION}-${TARGET}.${EXT}"
URL="https://github.com/${REPO}/releases/download/${RALPH_VERSION}/${ASSET}"
TMP="$(mktemp -d)"

echo "Downloading ${URL}"
curl -fsSL "$URL" -o "${TMP}/${ASSET}"

cd "$TMP"
tar xzf "$ASSET"

# ── Install ────────────────────────────────────────────────────────────────────
INSTALL_DIR="${RALPH_INSTALL:-}"

if [ -z "$INSTALL_DIR" ]; then
  if [ -w "/usr/local/bin" ]; then
    INSTALL_DIR="/usr/local/bin"
  else
    INSTALL_DIR="$HOME/.local/bin"
    mkdir -p "$INSTALL_DIR"
  fi
fi

EXTRACTED_DIR="${BINARY}-${RALPH_VERSION}-${TARGET}"
cp "${EXTRACTED_DIR}/${BINARY}" "${INSTALL_DIR}/${BINARY}"
chmod +x "${INSTALL_DIR}/${BINARY}"

# ── Cleanup ────────────────────────────────────────────────────────────────────
rm -rf "$TMP"

echo ""
echo "ralph ${RALPH_VERSION} installed to ${INSTALL_DIR}/${BINARY}"

# Warn if the install dir is not in PATH
case ":${PATH}:" in
  *":${INSTALL_DIR}:"*) ;;
  *)
    echo ""
    echo "NOTE: ${INSTALL_DIR} is not in your PATH."
    echo "Add this to your shell profile (~/.bashrc, ~/.zshrc, etc.):"
    echo "  export PATH=\"${INSTALL_DIR}:\$PATH\""
    ;;
esac
