#!/bin/bash

#########################
# Fix for the XCB issue #
#########################

sudo xhost +si:localuser:${USER}
export DISPLAY=:0

######################
# End of the XCB fix #
######################

## Supportive function to get app directory

function getpwd
{
    lnk="$(readlink -f $0)"
    ln="$(basename ${lnk})"
    ls=${#ln}

    ((ls=${ls}+1))
    ((ls=-${ls}))

    echo ${lnk::$ls}
}

## End of function


## Get the root folder

root="$(gwtpwd)"

# Create the link to the user home dir

if [ ! -d "${HOME}/.FreeCAD" -o ! -h "${HOME}/.FreeCAD" ]; then ln -vfs ${root} ${HOME}/.FreeCAD; fi

################################################################
#  TODO: Automatical discovery of the avaliable Python version #
################################################################

export PYTHONHOME=${root}

# Qt

export QT_XKB_CONFIG_ROOT=${LD_LIBRARY_PATH}:${root}/lib
# export QT_QPA_PLATFORM_PLUGIN_PATH=plugins
# export QTWEBENGINEPROCESS_PATH=libexec/QtWebEngineProcess

# Support for launching other applications from /usr/bin ( https://github.com/FreeCAD/FreeCAD-AppImage/issues/30)

if [ ! -z "$1" ] && [ -e "bin/$1" ] ; then
    MAIN="bin/$1" ; shift
else
    MAIN="bin/freecad"
fi

nice -n19 ${MAIN} "$@" &> ${root}/freecad.log &
