#!/bin/bash

export AXIOMA_ENV_BACKUP="$(env)"
DIR="$( cd "$( dirname "$0" )" && pwd )"
BASE_DIR=`readlink -f $DIR/..`
DISTRIB_ID=$(source /etc/os-release && echo "$ID" | xargs)
source "$DIR"/run-axioma-path
cd "$DIR/../bin"
gtk_desktop=("MATE" "LXQt" "XFCE" "X-Cinnamon")
gtk_distrib=("osnova")

if [[ (${gtk_desktop[@]} =~ $XDG_CURRENT_DESKTOP) || (${gtk_distrib[0]} =~ $DISTRIB_ID) ]]
then
   export QT_QPA_PLATFORMTHEME=gtk3
elif [[ $XDG_CURRENT_DESKTOP =~ "GNOME" ]]; then
   export QT_QPA_PLATFORMTHEME=gnome
else
   export QT_QPA_PLATFORMTHEME=xdgdesktopportal
fi

if [[ "wayland" == $XDG_SESSION_TYPE ]]; then
   export QT_QPA_PLATFORM="xcb;wayland" 
fi

./Axioma.GIS "$@"
err=$?

if [ $err -ne 0 ]; then
  echo "Exit with error code: $err"
  if [ $DISTRIB_ID == "osnova" ]; then
    flags="$(getfattr -d -m - $BASE_DIR/bin/Axioma.GIS | grep user.pax.flags)"
    if [ -z "$flags" ]; then
      echo "You need to run manually next commands:"
      echo "setfattr -n user.pax.flags -v m $BASE_DIR/bin/Axioma.GIS"
      echo "setfattr -n user.pax.flags -v m $BASE_DIR/bin/libprotection.so"
      echo "setfattr -n user.pax.flags -v m $BASE_DIR/bin/help"
      echo "setfattr -n user.pax.flags -v m $BASE_DIR/python/bin/python3"
      echo "setfattr -n user.pax.flags -v m $BASE_DIR/python/bin/pip"
      echo "setfattr -n user.pax.flags -v m $BASE_DIR/python/bin/pip3"
    fi
  fi
  exit $err
fi
