#!/bin/sh
# MongA!se per-user installer for Linux (Debian, Ubuntu, Fedora, Arch, …).
#
# Installs the AppImage into ~/.local/bin plus a desktop entry — no root
# required, works for every user, and the app keeps itself up to date
# via its built-in updater afterwards.
#
#   curl -fsSL https://install.mongaise.com | sh
#   sh install.sh --uninstall
#
# The base URL below must point to the directory containing latest.json.
set -eu

BASE_URL="${MONGAISE_BASE_URL:-https://update.mongaise.com}"

BIN_DIR="$HOME/.local/bin"
APP="$BIN_DIR/mongaise"
DESKTOP_DIR="$HOME/.local/share/applications"
ICON_DIR="$HOME/.local/share/icons/hicolor/128x128/apps"

if [ "${1:-}" = "--uninstall" ]; then
    rm -f "$APP" "$DESKTOP_DIR/mongaise.desktop" "$ICON_DIR/mongaise.png"
    echo "MongA!se removed."
    exit 0
fi

case "$(uname -m)" in
    x86_64 | amd64) ARCH="x86_64" ;;
    aarch64 | arm64) ARCH="aarch64" ;;
    *)
        echo "unsupported architecture: $(uname -m)" >&2
        exit 1
        ;;
esac

echo "Fetching manifest from $BASE_URL/latest.json …"
MANIFEST="$(curl -fsSL "$BASE_URL/latest.json")"

# Extract version + platform URL (python3 exists on all target distros).
URL="$(printf '%s' "$MANIFEST" | python3 -c "
import json, sys
m = json.load(sys.stdin)
platform = m['platforms'].get('linux-$ARCH')
if not platform:
    sys.exit('no linux-$ARCH build in the manifest')
print(m['version'])
print(platform['url'])
")"
VERSION="$(printf '%s' "$URL" | sed -n 1p)"
ARTIFACT="$(printf '%s' "$URL" | sed -n 2p)"
# The manifest lists the updater archive; the plain AppImage sits next
# to it on the server.
APPIMAGE_URL="${ARTIFACT%.tar.gz}"

echo "Installing MongA!se $VERSION (linux-$ARCH) …"
mkdir -p "$BIN_DIR" "$DESKTOP_DIR" "$ICON_DIR"
curl -fsSL -o "$APP.tmp" "$APPIMAGE_URL"
chmod +x "$APP.tmp"
mv "$APP.tmp" "$APP"

# Icon (optional — ignore failure) + desktop entry.
curl -fsSL -o "$ICON_DIR/mongaise.png" "$BASE_URL/icon.png" 2>/dev/null || true
cat > "$DESKTOP_DIR/mongaise.desktop" <<EOF
[Desktop Entry]
Type=Application
Name=MongA!se
Comment=Desktop cockpit for coding agents
Exec=$APP
Icon=mongaise
Terminal=false
Categories=Development;
EOF
command -v update-desktop-database >/dev/null 2>&1 \
    && update-desktop-database "$DESKTOP_DIR" >/dev/null 2>&1 || true

# AppImages need FUSE at runtime; hint when it is missing.
if ! { [ -e /usr/lib/libfuse.so.2 ] || [ -e /usr/lib64/libfuse.so.2 ] \
    || ldconfig -p 2>/dev/null | grep -q libfuse.so.2; }; then
    echo
    echo "Note: libfuse2 was not found. Install it (debian/ubuntu: libfuse2,"
    echo "fedora: fuse-libs, arch: fuse2) or run with:"
    echo "  $APP --appimage-extract-and-run"
fi

case ":$PATH:" in
    *":$BIN_DIR:"*) ;;
    *)
        echo
        echo "Note: $BIN_DIR is not on your PATH — add it to run 'mongaise'"
        echo "from the shell."
        ;;
esac

echo
echo "Done. Launch MongA!se from your app menu or run: $APP"
