#!/usr/bin/env bash
set -euo pipefail

# MCP Manager — Linux Installer
# Usage: curl -fsSL <url> | bash
#
# Prefers the .deb on Debian/Ubuntu (preserves the Chromium sandbox via a SUID
# chrome-sandbox); falls back to AppImage elsewhere, passing --no-sandbox since
# AppImage FUSE mounts are nosuid and Ubuntu 24.04+ AppArmor denies the
# unprivileged-userns fallback.

S3_BASE="https://hestiia-mcp-manager-releases.s3.eu-west-3.amazonaws.com"
APP_NAME="mcp-manager"

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

# --- 1. Pick install target ---

if command -v dpkg >/dev/null 2>&1 && command -v apt-get >/dev/null 2>&1; then
  TARGET_EXT="deb"
else
  TARGET_EXT="AppImage"
fi

# --- 2. Fetch release metadata ---

info "Fetching latest release info..."
LATEST_YML=$(curl -fsSL "$S3_BASE/latest-linux.yml")

VERSION=$(echo "$LATEST_YML" | grep -m1 '^version:' | sed 's/version: *//')
if [ -z "$VERSION" ]; then
  error "Could not parse version from latest-linux.yml"
fi
info "Latest version: $VERSION"

# Pick the file matching the chosen target. latest-linux.yml contains one
# 'files:' entry per build target; select the one whose url ends in .$TARGET_EXT.
FILENAME=$(echo "$LATEST_YML" \
  | awk '/^[[:space:]]*-[[:space:]]*url:/ { sub(/^[[:space:]]*-[[:space:]]*url:[[:space:]]*/, ""); print }' \
  | grep "\.${TARGET_EXT}\$" \
  | head -1)
if [ -z "$FILENAME" ]; then
  error "No .$TARGET_EXT artifact found in latest-linux.yml (does the current release publish both targets?)"
fi

# Extract the sha512 that follows the matching url. awk tracks which file block
# we're inside by comparing each '- url:' line against the chosen filename.
SHA512=$(echo "$LATEST_YML" | awk -v target="$FILENAME" '
  /^[[:space:]]*-[[:space:]]*url:/ {
    sub(/^[[:space:]]*-[[:space:]]*url:[[:space:]]*/, "");
    match_url = ($0 == target);
    next
  }
  match_url && /^[[:space:]]*sha512:/ {
    sub(/^[[:space:]]*sha512:[[:space:]]*/, "");
    print;
    exit
  }
')
if [ -z "$SHA512" ]; then
  error "Could not find sha512 for $FILENAME in latest-linux.yml"
fi

# --- 3. Download + verify ---

TMPFILE=$(mktemp --suffix=".$TARGET_EXT")
trap 'rm -f "$TMPFILE"' EXIT

info "Downloading $FILENAME..."
curl -fSL "$S3_BASE/$FILENAME" -o "$TMPFILE"

info "Verifying checksum..."
ACTUAL_HASH=$(sha512sum "$TMPFILE" | cut -d' ' -f1)
# latest-linux.yml stores base64-encoded sha512; convert to hex for comparison.
EXPECTED_HEX=$(python3 -c "import base64,sys; sys.stdout.write(base64.b64decode('$SHA512').hex())")
if [ "$ACTUAL_HASH" != "$EXPECTED_HEX" ]; then
  error "Checksum verification failed. The download may be corrupted."
fi

# --- 4. Install ---

if [ "$TARGET_EXT" = "deb" ]; then
  info "Installing via apt (sudo required)..."
  # apt-get install from a file path resolves dependencies automatically and
  # runs the .deb's postinst, which chmod 4755's chrome-sandbox for us.
  sudo apt-get install -y "$TMPFILE"

  info ""
  info "MCP Manager $VERSION installed successfully!"
  info ""
  info "  Binary:     /opt/mcp-manager/mcp-manager"
  info "  Menu entry: /usr/share/applications/mcp-manager.desktop"
  info ""
  info "Launch from your application menu, or run: mcp-manager"
else
  INSTALL_DIR="$HOME/.local/bin"
  APP_DIR="$HOME/.local/share/applications"
  AUTOSTART_DIR="$HOME/.config/autostart"
  INSTALL_PATH="$INSTALL_DIR/$APP_NAME.AppImage"

  # libsecret-1-0 is required at runtime for Electron's safeStorage (keychain
  # access). On Debian systems we can check with dpkg; elsewhere we just warn.
  if command -v dpkg >/dev/null 2>&1 && ! dpkg -s libsecret-1-0 >/dev/null 2>&1; then
    error "libsecret-1-0 is required but not installed.
  Run: sudo apt-get install -y libsecret-1-0
  Then re-run this installer."
  fi

  mkdir -p "$INSTALL_DIR" "$APP_DIR" "$AUTOSTART_DIR"
  install -m 755 "$TMPFILE" "$INSTALL_PATH"

  # --no-sandbox in the Exec= lines: AppImage FUSE mounts are nosuid so the
  # bundled chrome-sandbox's SUID bit can't take effect, and Ubuntu 24.04+
  # AppArmor denies the userns fallback. Without --no-sandbox, the app crashes
  # before any JS runs, and the protocol-handler invocation for OAuth callbacks
  # crashes too — the URL never reaches the running instance.
  DESKTOP_ENTRY="[Desktop Entry]
Type=Application
Name=MCP Manager
Comment=Policy-enforcing MCP proxy for Claude Code
Exec=\"$INSTALL_PATH\" --no-sandbox
Icon=$APP_NAME
Terminal=false
Categories=Development;
StartupNotify=false"

  echo "$DESKTOP_ENTRY" > "$APP_DIR/$APP_NAME.desktop"
  printf '%s\nX-GNOME-Autostart-enabled=true\nHidden=false\n' "$DESKTOP_ENTRY" \
    > "$AUTOSTART_DIR/$APP_NAME.desktop"

  info ""
  info "MCP Manager $VERSION installed successfully!"
  info ""
  info "  Binary:    $INSTALL_PATH"
  info "  Menu:      $APP_DIR/$APP_NAME.desktop"
  info "  Autostart: $AUTOSTART_DIR/$APP_NAME.desktop"
  info ""
  info "Run it now:  $INSTALL_PATH --no-sandbox"
  info "Or find 'MCP Manager' in your application menu."
fi
