#!/usr/bin/env bash
# Install LM Studio on AlmaLinux 9.
#
# AlmaLinux 9 ships GCC 11 → libstdc++ provides up to GLIBCXX_3.4.29.
# LM Studio bundles watcher.node (compiled with GCC 12) which requires
# _ZNSt18condition_variable4waitERSt11unique_lockISt5mutexE@GLIBCXX_3.4.30.
# That symbol exists in the system libstdc++ under GLIBCXX_3.4.11.
#
# Fix: ELF-patch watcher.node to rewrite the VERNEED entry from
# GLIBCXX_3.4.30 → GLIBCXX_3.4.11 (same symbol, correct version tag).
# Both vna_hash and the version string are updated in-place.

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

# Ansible copy task places files in /tmp
if [ -f "/tmp/patch-glibcxx-compat.py" ]; then
    PATCHER="/tmp/patch-glibcxx-compat.py"
else
    PATCHER="${SCRIPT_DIR}/patch-glibcxx-compat.py"
fi

# --- Fetch installer metadata ---
echo "[lmstudio-install] Fetching installer metadata..."
INSTALL_SH=$(curl -fsSL https://lmstudio.ai/install.sh)
VERSION=$(echo "$INSTALL_SH" | grep '^APP_VERSION=' | cut -d'"' -f2)
ARTIFACT_URL_BASE=$(echo "$INSTALL_SH" | grep '^ARTIFACT_DOWNLOAD_URL=' | cut -d'"' -f2)

ARTIFACT="${VERSION}-linux-x64.full.tar.gz"
URL="https://${ARTIFACT_URL_BASE}/${ARTIFACT}"

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

echo "[lmstudio-install] Downloading ${ARTIFACT}..."
curl -fsSL "$URL" -o "$TMPDIR/bundle.tar.gz"

echo "[lmstudio-install] Extracting bundle..."
tar xf "$TMPDIR/bundle.tar.gz" -C "$TMPDIR"

# Patch watcher.node before bootstrap so the daemon never sees GLIBCXX_3.4.30
echo "[lmstudio-install] Patching watcher.node (GLIBCXX_3.4.30 → GLIBCXX_3.4.11)..."
find "$TMPDIR" -name 'watcher.node' | while read -r node; do
    python3 "$PATCHER" "$node"
done

echo "[lmstudio-install] Running bootstrap..."
LMS_BOOTSTRAP_INSTALL_SH=1 "$TMPDIR/llmster" bootstrap

# Also patch the installed copy in ~/.lmstudio after bootstrap
echo "[lmstudio-install] Patching installed watcher.node copies..."
find "${HOME}/.lmstudio" -name 'watcher.node' 2>/dev/null | while read -r node; do
    python3 "$PATCHER" "$node"
done

echo "[lmstudio-install] Installation complete."
