#!/bin/sh

# fix_cura_for_deb13.sh
# 2025-09-22
# by Gernot Walzl

# This script generates a working AppImage of Cura to fix the following error:
# Could not initialize GLX
# https://github.com/Ultimaker/Cura/issues/19837
# https://github.com/Ultimaker/Cura/issues/20706

CURA_VERSION=${CURA_VERSION:-'5.10.2'}
CURA_APPIMG="UltiMaker-Cura-$CURA_VERSION-linux-X64.AppImage"
CURA_DOWNLOAD="https://github.com/Ultimaker/Cura/releases/download/$CURA_VERSION/$CURA_APPIMG"

LIBZ3_PKG="libz3-4_4.8.12-3.1_amd64.deb"  # from Debian 12
LIBZ3_DOWNlOAD="http://ftp.de.debian.org/debian/pool/main/z/z3/$LIBZ3_PKG"

APPIMAGETOOL="appimagetool-x86_64.AppImage"
APPIMAGETOOL_DOWNLOAD="https://github.com/AppImage/appimagetool/releases/download/1.9.0/$APPIMAGETOOL"

CWD=$(pwd)
TMP=${TMP:-'/tmp'}

set -e

if [ ! -f "$CURA_APPIMG" ]; then
  wget -O "$CURA_APPIMG" "$CURA_DOWNLOAD"
fi
if [ ! -f "$LIBZ3_PKG" ]; then
  wget -O "$LIBZ3_PKG" "$LIBZ3_DOWNlOAD"
fi
if [ ! -f "$APPIMAGETOOL" ]; then
  wget -O "$APPIMAGETOOL" "$APPIMAGETOOL_DOWNLOAD"
fi

chmod +x "$CWD/$CURA_APPIMG"
chmod +x "$CWD/$APPIMAGETOOL"

mkdir -p "$TMP/cura"
cd "$TMP/cura" || exit 1

"$CWD/$CURA_APPIMG" --appimage-extract

ar x "$CWD/$LIBZ3_PKG" data.tar.xz
tar xvf data.tar.xz './usr/lib/x86_64-linux-gnu/libz3.so.4'
mv './usr/lib/x86_64-linux-gnu/libz3.so.4' squashfs-root
sed -i 's/Icon=cura-icon.png/Icon=cura-icon/' \
  squashfs-root/com.ultimaker.cura.desktop

cd "$CWD" || exit 1
"$CWD/$APPIMAGETOOL" "/tmp/cura/squashfs-root" \
  "UltiMaker-Cura-$CURA_VERSION-deb13-X64.AppImage"

rm -rf "$TMP/cura"