#!/usr/bin/env bash
# Nylas CLI installer
# Usage: curl -fsSL https://cli.nylas.com/install.sh | bash
#
# Detects OS and architecture, downloads the latest release from GitHub,
# verifies the SHA-256 checksum, and installs to ~/.nylas/bin.

set -euo pipefail

REPO="nylas/cli"
INSTALL_DIR="${NYLAS_INSTALL_DIR:-$HOME/.nylas/bin}"

# --- helpers ----------------------------------------------------------------

die() { printf '\033[1;31merror:\033[0m %s\n' "$1" >&2; exit 1; }
info() { printf '\033[1;32m==>\033[0m %s\n' "$1"; }

need() {
  command -v "$1" >/dev/null 2>&1 || die "'$1' is required but not found"
}

# --- detect OS and arch -----------------------------------------------------

detect_platform() {
  local os arch

  case "$(uname -s)" in
    Linux*)  os="linux" ;;
    Darwin*) os="darwin" ;;
    MINGW*|MSYS*|CYGWIN*) os="windows" ;;
    *) die "unsupported operating system: $(uname -s)" ;;
  esac

  case "$(uname -m)" in
    x86_64|amd64)  arch="amd64" ;;
    arm64|aarch64) arch="arm64" ;;
    *) die "unsupported architecture: $(uname -m)" ;;
  esac

  PLATFORM_OS="$os"
  PLATFORM_ARCH="$arch"
}

# --- fetch latest version ---------------------------------------------------

fetch_latest_version() {
  need curl
  local url="https://api.github.com/repos/${REPO}/releases/latest"
  VERSION="$(curl -fsSL "$url" | grep '"tag_name"' | sed -E 's/.*"v([^"]+)".*/\1/')"
  [ -n "$VERSION" ] || die "could not determine latest version"
}

# --- download, verify, install ----------------------------------------------

install() {
  need curl
  need tar

  local ext="tar.gz"
  [ "$PLATFORM_OS" = "windows" ] && ext="zip"

  local filename="nylas_${VERSION}_${PLATFORM_OS}_${PLATFORM_ARCH}.${ext}"
  local base_url="https://github.com/${REPO}/releases/download/v${VERSION}"
  local archive_url="${base_url}/${filename}"
  local checksums_url="${base_url}/checksums.txt"

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

  info "Downloading Nylas CLI v${VERSION} (${PLATFORM_OS}/${PLATFORM_ARCH})"
  curl -fsSL -o "${tmpdir}/${filename}" "$archive_url" ||
    die "download failed: ${archive_url}"

  # verify checksum
  info "Verifying checksum"
  curl -fsSL -o "${tmpdir}/checksums.txt" "$checksums_url" ||
    die "could not fetch checksums"

  local expected
  expected="$(grep -F "$filename" "${tmpdir}/checksums.txt" | awk '{print $1}')"
  [ -n "$expected" ] || die "no checksum found for ${filename}"

  local actual
  if command -v sha256sum >/dev/null 2>&1; then
    actual="$(sha256sum "${tmpdir}/${filename}" | awk '{print $1}')"
  elif command -v shasum >/dev/null 2>&1; then
    actual="$(shasum -a 256 "${tmpdir}/${filename}" | awk '{print $1}')"
  else
    die "no sha256sum or shasum found — cannot verify checksum"
  fi

  [ "$actual" = "$expected" ] || die "checksum mismatch: expected ${expected}, got ${actual}"

  # extract
  info "Installing to ${INSTALL_DIR}"
  mkdir -p "$INSTALL_DIR"

  if [ "$ext" = "tar.gz" ]; then
    tar -xzf "${tmpdir}/${filename}" -C "${tmpdir}"
  else
    need unzip
    unzip -qo "${tmpdir}/${filename}" -d "${tmpdir}"
  fi

  # the archive contains a 'nylas' binary at the top level
  cp "${tmpdir}/nylas" "${INSTALL_DIR}/nylas"
  chmod +x "${INSTALL_DIR}/nylas"

  # --- shell PATH guidance --------------------------------------------------

  info "Nylas CLI v${VERSION} installed to ${INSTALL_DIR}/nylas"

  if ! echo "$PATH" | tr ':' '\n' | grep -qx "$INSTALL_DIR"; then
    printf '\n'
    printf '  Add Nylas CLI to your PATH:\n'
    printf '\n'
    printf '    # bash\n'
    printf '    echo '\''export PATH="%s:$PATH"'\'' >> ~/.bashrc && source ~/.bashrc\n' "$INSTALL_DIR"
    printf '\n'
    printf '    # zsh\n'
    printf '    echo '\''export PATH="%s:$PATH"'\'' >> ~/.zshrc && source ~/.zshrc\n' "$INSTALL_DIR"
    printf '\n'
    printf '    # or for this session only\n'
    printf '    export PATH="%s:$PATH"\n' "$INSTALL_DIR"
    printf '\n'
  fi

  info "Run 'nylas auth login' to get started"
}

# --- main -------------------------------------------------------------------

detect_platform
fetch_latest_version
install
