#!/bin/bash

version=2.8.1

install_packages git mesa-utils libcurl4 libgtk-3-0 zlib1g libdbus-1-3 libxcb1 libxi6 libxfixes3 libatk-bridge2.0-0 libepoxy0 libxinerama1 libxrandr2 libxcursor1 libxcomposite1 libxdamage1 libxkbcommon0 libxcb-shm0 libxcb-render0 libpcre3 libxau6 libxdmcp6 libatspi2.0-0 libexpat1 liblzma5 libbsd0 libgpg-error0 || exit 1
# note, libffi.so.6 is linked by the binary and not provided in the appimage (appimage contains libffi.so.7). this appimage probably never worked on bullseye

wget -O /tmp/PrusaSlicer.AppImage "https://github.com/davidk/PrusaSlicer-ARM.AppImage/releases/download/version_${version}/PrusaSlicer-version_${version}-aarch64.AppImage" || error "Failed to download appimage!"
sudo mv /tmp/PrusaSlicer.AppImage /opt || error "Failed to move appimage to install location!"
sudo chmod +x /opt/PrusaSlicer.AppImage || error "Failed to mark as executable!"
sudo chown root:root /opt/PrusaSlicer.AppImage || error "Failed to set appimage ownership!"

enable_module fuse || exit 1

if ! grep -qF 'PrusaSlicer.desktop' ~/.config/mimeapps.list ;then
  echo "Associating the STL mimetype for PrusaSlicer..."
  echo "[Added Associations]
model/stl=PrusaSlicer.desktop;" >> ~/.config/mimeapps.list
fi

function version { echo "$@" | awk -F. '{ printf("%d%03d%03d\n", $1,$2,$3); }'; }
# detect if script is running on a system with OpenGL lower than 3.3
if [ $(version $(glxinfo -B | sed -n "s/^OpenGL version string://p" | awk '{ print $1 }')) -lt $(version "3.3.0") ]; then
  warning "You are running a device that is not OpenGL 3.3 compliant or the OpenGL version could not be determined.\nAdding a MESA_GL_VERSION_OVERRIDE to 3.3"
  #add the MESA override to the .desktop file
  exec='env MESA_GL_VERSION_OVERRIDE=3.3 /opt/PrusaSlicer.AppImage %F'
else
  exec='/opt/PrusaSlicer.AppImage %F'
fi

sudo rm -f /usr/local/share/applications/PrusaSlicer.desktop
echo "[Desktop Entry]
Name=PrusaSlicer
GenericName=3D Printing Software
Comment=PrusaSlicer converts 3D models into paths for a 3D printer. It prepares your print for maximum accuracy, minimum printing time and good reliability with many extra features that make your print come out great.
Exec=$exec
Icon=$(dirname $0)/icon-64.png
Terminal=false
Type=Application
MimeType=application/sla;application/vnd.ms-3mfdocument;application/prs.wavefront-obj;image/bmp;image/gif;image/jpeg;image/png;model/x3d+xml;model/stl;
Categories=Graphics;Education;Development;Science;
Keywords=3D;Printing;
StartupNotify=true" | sudo tee /usr/share/applications/PrusaSlicer.desktop >/dev/null || error "Failed to create menu button!"
