#!/usr/bin/bash
# Download LM Studio's AppImage from lmstudio.ai and unpack it into
# /usr/lib64/lm-studio/app. LM Studio's terms don't allow redistributing it, so the RPM
# carries only this installer; %post runs it on install and on every update.
# Run it again as root if the download failed: /usr/libexec/lm-studio-install
set -euo pipefail

version=0.4.28-2
url=https://installers.lmstudio.ai/linux/arm64/0.4.28-2/LM-Studio-0.4.28-2-arm64.AppImage
sha256=8a99806356e167844c929dae30d49f8be8c48a0aaf6895d17e85163c6635bcd3
dir=/usr/lib64/lm-studio

if [[ $(cat "$dir/app/.version" 2>/dev/null) == "$version" ]]; then
    echo "LM Studio $version is already installed"
    exit 0
fi
(( EUID == 0 )) || { echo "run this as root" >&2; exit 1; }

tmp=$(mktemp -d /var/tmp/lm-studio.XXXXXX)
trap 'rm -rf "$tmp" "$dir/app.new"' EXIT

echo "Downloading LM Studio $version (about 1 GB)..."
curl -fL --retry 3 --progress-bar -o "$tmp/lm-studio.AppImage" "$url"
echo "$sha256  $tmp/lm-studio.AppImage" | sha256sum -c --quiet

# The AppImage is an ELF runtime followed by a squashfs image, which starts
# where the ELF section headers end: e_shoff + e_shentsize * e_shnum.
# Unpacking it with unsquashfs avoids running the downloaded file as root.
appimage=$tmp/lm-studio.AppImage
field() { od -An -t "u$2" -j "$1" -N "$2" "$appimage" | tr -d ' '; }
offset=$(( $(field 40 8) + $(field 58 2) * $(field 60 2) ))

echo "Unpacking..."
rm -rf "$dir/app.new"
unsquashfs -q -no-xattrs -o "$offset" -d "$dir/app.new" "$appimage" >/dev/null
echo "$version" > "$dir/app.new/.version"

rm -rf "$dir/app.old"
[[ -d "$dir/app" ]] && mv "$dir/app" "$dir/app.old"
mv "$dir/app.new" "$dir/app"
rm -rf "$dir/app.old"
echo "LM Studio $version installed"
