#!/bin/sh
# ═══════════════════════════════════════════════════════════════════
#  Rustty — instalador para Linux y macOS
#  Uso: curl -sSf https://rustty.es/install.sh | sh
#
#  Detecta tu sistema, descarga el paquete nativo del último release
#  publicado en GitHub e invoca al gestor de paquetes adecuado.
#
#  Linux:
#    - Arch / Manjaro / EndeavourOS  → .pkg.tar.zst (pacman -U)
#    - Debian / Ubuntu / Mint        → .deb        (apt install)
#    - Fedora / RHEL / CentOS        → .rpm        (dnf install)
#    - openSUSE / SUSE               → .rpm        (zypper install)
#    - Otras                         → AppImage en ~/.local/bin
#
#  macOS (Apple Silicon):
#    - Descarga .app.tar.gz y lo extrae en ~/Applications/Rustty.app
# ═══════════════════════════════════════════════════════════════════

set -eu

OWNER="Aleixenandros"
REPO="Rustty"
API="https://api.github.com/repos/${OWNER}/${REPO}/releases/latest"

# ─── Helpers ────────────────────────────────────────────────────────
if [ -t 1 ]; then
  C_RST='\033[0m'
  C_INFO='\033[0;36m'
  C_OK='\033[0;32m'
  C_ERR='\033[0;31m'
  C_WARN='\033[0;33m'
else
  C_RST=''; C_INFO=''; C_OK=''; C_ERR=''; C_WARN=''
fi

log()  { printf "${C_INFO}::${C_RST} %s\n" "$*"; }
ok()   { printf "${C_OK}✓${C_RST}  %s\n" "$*"; }
warn() { printf "${C_WARN}!${C_RST}  %s\n" "$*"; }
err()  { printf "${C_ERR}✗${C_RST}  %s\n" "$*" >&2; exit 1; }

need() { command -v "$1" >/dev/null 2>&1 || err "Falta el comando: $1"; }

# ─── Comprobaciones previas ─────────────────────────────────────────
need curl
need uname

OS_NAME=$(uname -s)
ARCH_RAW=$(uname -m)

case "$OS_NAME" in
  Linux)  OS=linux ;;
  Darwin) OS=macos ;;
  *) err "Sistema no soportado: $OS_NAME (solo Linux y macOS)" ;;
esac

# ─── Detectar familia / arquitectura ────────────────────────────────
detect_family() {
  if [ -r /etc/os-release ]; then
    # shellcheck disable=SC1091
    . /etc/os-release
    LOWER=$(printf '%s %s' "${ID:-}" "${ID_LIKE:-}" | tr '[:upper:]' '[:lower:]')
    case "$LOWER" in
      *arch*|*manjaro*|*endeavour*) echo arch; return ;;
      *opensuse*|*suse*)            echo suse; return ;;
      *debian*|*ubuntu*|*mint*)     echo debian; return ;;
      *fedora*|*rhel*|*centos*|*rocky*|*alma*) echo fedora; return ;;
    esac
  fi
  echo appimage
}

# ─── Última versión ─────────────────────────────────────────────────
log "Consultando la última versión publicada..."
TAG=$(curl -sSfL "$API" | sed -n 's/.*"tag_name":[[:space:]]*"\([^"]*\)".*/\1/p' | head -n1)
[ -n "$TAG" ] || err "No se pudo obtener la última versión desde GitHub"
VERSION="${TAG#v}"
ok "Última versión: $TAG"

# ─── Selección de asset según OS ────────────────────────────────────
if [ "$OS" = "linux" ]; then
  case "$ARCH_RAW" in
    x86_64|amd64) ;;
    *) err "Arquitectura Linux no soportada: $ARCH_RAW (hoy solo x86_64)" ;;
  esac
  FAMILY=$(detect_family)
  log "Distribución detectada: ${FAMILY}"

  case "$FAMILY" in
    arch)
      ASSET="Rustty-${VERSION}-1-x86_64.pkg.tar.zst"
      INSTALL="sudo pacman -U --noconfirm"
      ;;
    debian)
      ASSET="Rustty_${VERSION}_amd64.deb"
      INSTALL="sudo apt-get install -y"
      ;;
    fedora)
      ASSET="Rustty-${VERSION}-1.x86_64.rpm"
      INSTALL="sudo dnf install -y"
      ;;
    suse)
      ASSET="Rustty-${VERSION}-1.x86_64.rpm"
      INSTALL="sudo zypper install -y --allow-unsigned-rpm"
      ;;
    *)
      ASSET="Rustty_${VERSION}_amd64.AppImage"
      INSTALL=""
      ;;
  esac

else
  # macOS
  case "$ARCH_RAW" in
    arm64|aarch64) ;;
    x86_64) err "Intel Mac no se distribuye precompilado. Compila desde fuente: https://github.com/${OWNER}/${REPO}#desarrollo-y-construcción" ;;
    *) err "Arquitectura macOS no soportada: $ARCH_RAW" ;;
  esac
  ASSET="Rustty_aarch64.app.tar.gz"
  INSTALL=""
fi

URL="https://github.com/${OWNER}/${REPO}/releases/download/${TAG}/${ASSET}"
TMP=$(mktemp -d)
trap 'rm -rf "$TMP"' EXIT INT TERM

log "Descargando ${ASSET}..."
if ! curl -sSfL --progress-bar -o "$TMP/$ASSET" "$URL"; then
  err "Descarga fallida: $URL"
fi
ok "Descargado en $TMP/$ASSET"

# ─── Instalación ────────────────────────────────────────────────────
if [ "$OS" = "macos" ]; then
  DEST_DIR="${HOME}/Applications"
  mkdir -p "$DEST_DIR"

  log "Extrayendo Rustty.app..."
  tar -xzf "$TMP/$ASSET" -C "$TMP" || err "No se pudo descomprimir el bundle"
  [ -d "$TMP/Rustty.app" ] || err "El archivo no contiene Rustty.app"

  if [ -d "$DEST_DIR/Rustty.app" ]; then
    log "Quitando versión previa en $DEST_DIR/Rustty.app"
    rm -rf "$DEST_DIR/Rustty.app"
  fi
  mv "$TMP/Rustty.app" "$DEST_DIR/Rustty.app"
  # Elimina cuarentena por si la hubiera (firmado + notarizado, normalmente no es necesario)
  xattr -dr com.apple.quarantine "$DEST_DIR/Rustty.app" 2>/dev/null || true

  ok "Rustty $TAG instalado en $DEST_DIR/Rustty.app"
  echo
  printf "Abre con: ${C_INFO}open '$DEST_DIR/Rustty.app'${C_RST}\n"
  printf "O desde Spotlight (⌘Espacio → Rustty).\n"
  printf "Si prefieres tenerlo en /Applications: ${C_INFO}sudo mv '$DEST_DIR/Rustty.app' /Applications/${C_RST}\n"

elif [ -n "$INSTALL" ]; then
  log "Instalando con: $INSTALL <paquete>"
  # shellcheck disable=SC2086
  $INSTALL "$TMP/$ASSET"
  ok "Rustty $TAG instalado."
  echo
  printf "Lánzalo con: ${C_INFO}rustty${C_RST}  o búscalo en tu menú de aplicaciones.\n"
else
  DEST="${HOME}/.local/bin"
  mkdir -p "$DEST"
  install -m 0755 "$TMP/$ASSET" "$DEST/rustty"
  ok "AppImage instalada en $DEST/rustty"
  case ":$PATH:" in
    *":$DEST:"*) ;;
    *) warn "$DEST no está en \$PATH. Añade a tu shell: export PATH=\"$DEST:\$PATH\"" ;;
  esac
  echo
  printf "Lánzalo con: ${C_INFO}rustty${C_RST}\n"
fi
