#!/bin/bash

version=2.9.6

install_packages git mesa-utils || exit 1

wget -O /tmp/PrusaSlicer.AppImage "https://github.com/davidk/PrusaSlicer-ARM.AppImage/releases/download/version_${version}/PrusaSlicer-${version}-aarch64-full.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!"
