#!/bin/sh

# errors shouldn't cause script to exit
set +e

# set chrome-sandbox permissions
chmod 4755 ${CMAKE_INSTALL_PREFIX}/chrome-sandbox

# create softlink to rstudio /usr/bin
ln -f -s ${CMAKE_INSTALL_PREFIX}/rstudio /usr/bin/rstudio

# create symlinks in Yaru icon themes to work around Ubuntu bug
# where Nautilus doesn't fall back to hicolor for MIME type icons
# (https://gitlab.gnome.org/GNOME/nautilus/-/issues/2190)
for theme_dir in /usr/share/icons/Yaru*; do
   if [ -d "$theme_dir" ]; then
      for size in 16x16 24x24 32x32 48x48 256x256; do
         hicolor_dir="/usr/share/icons/hicolor/$size/mimetypes"
         if [ -d "$hicolor_dir" ]; then
            mime_dir="$theme_dir/$size/mimetypes"
            mkdir -p "$mime_dir"
            for icon in "$hicolor_dir"/application-x-r-*.png "$hicolor_dir"/text-x-r-*.png "$hicolor_dir"/text-x-quarto-*.png; do
               if [ -f "$icon" ]; then
                  ln -sf "$icon" "$mime_dir/$(basename "$icon")"
               fi
            done
         fi
      done
   fi
done

# refresh mime database and icon cache
if command -v update-mime-database > /dev/null; then
   if ! update-mime-database /usr/share/mime > /dev/null; then
      echo "rstudio postinst: warning: update-mime-database failed" >&2
   fi
fi
if command -v gtk-update-icon-cache > /dev/null; then
   if ! gtk-update-icon-cache -f -t /usr/share/icons/hicolor > /dev/null; then
      echo "rstudio postinst: warning: gtk-update-icon-cache failed for hicolor" >&2
   fi
   for theme_dir in /usr/share/icons/Yaru*; do
      if [ -f "$theme_dir/index.theme" ]; then
         if ! gtk-update-icon-cache -f -t "$theme_dir" > /dev/null; then
            echo "rstudio postinst: warning: gtk-update-icon-cache failed for $theme_dir" >&2
         fi
      fi
   done
fi

# clear error termination state
set -e
