#!/bin/bash
# Installs the latest Magnum for Linux (x86_64 or aarch64) for the current user:
#   curl -fsSL https://magnumade.com/linux/install.sh | bash
# It downloads the release archive from GitHub and runs the installer inside it, which puts
# `magnum` in ~/.local/bin with a desktop entry and icon. Magnum then updates itself.
set -euo pipefail

if [ -t 1 ]; then GREEN='\033[0;32m'; YELLOW='\033[1;33m'; RED='\033[0;31m'; DIM='\033[2m'; NC='\033[0m'; else GREEN=""; YELLOW=""; RED=""; DIM=""; NC=""; fi
step() { echo -e "${YELLOW}›${NC} $*"; }
ok()   { echo -e "${GREEN}✓${NC} $*"; }
err()  { echo -e "${RED}✗${NC} $*" >&2; }

[ "$(uname -s)" = Linux ] || { err "This installer is for Linux. On a Mac: curl -fsSL https://magnumade.com/macos/install.sh | bash"; exit 1; }
case "$(uname -m)" in
  x86_64|amd64) ARCH=x86_64 ;;
  aarch64|arm64) ARCH=aarch64 ;;
  *) err "Magnum for Linux is built for x86_64 and aarch64, not $(uname -m)"; exit 1 ;;
esac

REPO=wenod/magnum-exp
step "Finding the latest release…"
# The latest release's tag, from where GitHub redirects /releases/latest (no API, no rate limit).
LATEST=$(curl -fsSL -o /dev/null -w '%{url_effective}' "https://github.com/$REPO/releases/latest") || { err "Couldn't reach GitHub's releases"; exit 1; }
TAG=${LATEST##*/}
case "$TAG" in v[0-9]*) ;; *) err "Couldn't find the latest release"; exit 1 ;; esac
URL="https://github.com/$REPO/releases/download/$TAG/Magnum-linux-$ARCH.tar.gz"

TMP=$(mktemp -d)
trap 'rm -rf "$TMP"' EXIT
step "Downloading Magnum $TAG for $ARCH…"
curl -fL --progress-bar -o "$TMP/magnum.tar.gz" "$URL" || { err "No Linux $ARCH build in $TAG"; exit 1; }
echo -e "${DIM}SHA256: $(sha256sum "$TMP/magnum.tar.gz" | cut -d' ' -f1)${NC}"
tar -xzf "$TMP/magnum.tar.gz" -C "$TMP"
bash "$TMP/magnum/install.sh"
ok "Magnum $TAG is installed. Open it from your applications menu, or run: magnum"
command -v claude >/dev/null || command -v codex >/dev/null || command -v pi >/dev/null || echo -e "${DIM}Magnum runs Claude Code, Codex or Pi: install one from its start screen${NC}"
