#!/bin/bash

# Main AppImage internal startup script.
# Wrap XDG_* variables properly for Qt.
#
# SPDX-FileCopyrightText: 2015-2024 by Gilles Caulier <caulier dot gilles at gmail dot com>
#
# SPDX-License-Identifier: BSD-3-Clause
#

# Function to preload a shared library in memory before to start application.

preload_shared_library ()
{
    FILE=$1
    echo -e "Check library $FILE"

#    if   [ -f "$DIR/usr/lib64/$FILE" ] ; then
#        export LD_PRELOAD=$LD_PRELOAD:$DIR/usr/lib64/$FILE
#    elif
    if   [ -f "/usr/lib64/$FILE" ] ; then
        export LD_PRELOAD=$LD_PRELOAD:/usr/lib64/$FILE
    elif [ -f "/usr/lib/x86_64-linux-gnu/$FILE" ] ; then
        export LD_PRELOAD=$LD_PRELOAD:/usr/lib/x86_64-linux-gnu/$FILE
    elif [ -f "/lib/x86_64-linux-gnu/$FILE" ] ; then
        export LD_PRELOAD=$LD_PRELOAD:/lib/x86_64-linux-gnu/$FILE
    fi
}

###

echo "-- digiKam Linux AppImage Bundle"
echo "-- Use 'help' as CLI argument to know all available options for digiKam application."
echo "-- Notes: to integrate this bundle to your desktop, use AppImageLauncher."
echo "--        to enable all debug messages on the console, use 'export QT_LOGGING_RULES=\"digikam*=true\"'."
echo "--        to extract the bundle contents locally, use option '--appimage-extract' on the command line."

if [[ "$(uname -m)" != "x86_64" ]] ; then

    echo "!!! You trying to run a 64 bits binary on a 32 bits system. Aborted !!!"
    exit -1;

fi

# Show host OS name and version.

OS_NAME=$(awk '/DISTRIB_ID=/' /etc/*-release | sed 's/DISTRIB_ID=//' | sed 's/\"//' | sed 's/\"//' | tr '[:upper:]' '[:lower:]')
OS_ARCH=$(uname -m | sed 's/x86_//;s/i[3-6]86/32/')
OS_VERSION=$(awk '/DISTRIB_RELEASE=/' /etc/*-release | sed 's/DISTRIB_RELEASE=//' | sed 's/[.]0/./')

if [ -z "${OS_NAME}" ] ; then

    OS_NAME=$(awk -F'=' '/PRETTY_NAME/ {print $2}' /etc/os-release | tr -d '"')

fi

if [ -z "${OS_VERSION}" ] ; then

    OS_VERSION=$(awk -F'=' '/VERSION_ID/ {print $2}' /etc/os-release | tr -d '"')

fi

echo "-- Detected host Linux $OS_NAME-$OS_ARCH-$OS_VERSION"

# See bugs #414016, #414028, #415882, Qt fill log files with unwanted
# debug trace about locale rules.

export QT_LOGGING_RULES="default*=false;"$QT_LOGGING_RULES

# Try to make Qt apps more "native looking" on Gtk-based desktops, if possible
# see https://github.com/AppImage/AppImageKit/issues/977#issue-462374883

case "${XDG_CURRENT_DESKTOP}" in

    *GNOME*|*gnome*|*XFCE*)
        export QT_QPA_PLATFORMTHEME=gtk2
        ;;

esac

DIR="`dirname \"$0\"`"
DIR="`( cd \"$DIR\" && readlink -f $(pwd) )`"
echo "-- AppImage mounted directory: $DIR"
export APPDIR=$DIR

# Note: these variables are used in patched Qt to detect AppImage session.

export APPIMAGE_ORIGINAL_LD_LIBRARY_PATH=$LD_LIBRARY_PATH
export APPIMAGE_ORIGINAL_QT_PLUGIN_PATH=$QT_PLUGIN_PATH
export APPIMAGE_ORIGINAL_XDG_DATA_DIRS=$XDG_DATA_DIRS
export APPIMAGE_ORIGINAL_LD_PRELOAD=$LD_PRELOAD
export APPIMAGE_ORIGINAL_PATH=$PATH

export LD_LIBRARY_PATH=$DIR/usr/lib/:$LD_LIBRARY_PATH
export QT_PLUGIN_PATH=$DIR/usr/plugins/

# See bug #427906

if [ -d "/usr/share/X11/xkb/" ] ; then

    export XKB_CONFIG_ROOT=/usr/share/X11/xkb/

fi

export XDG_DATA_DIRS=$DIR/usr/share/:$XDG_DATA_DIRS
export PATH=$DIR/usr/bin:$DIR/usr/lib:$DIR/usr/lib/libexec/kf5:$DIR/usr/share/digikam/utils:$PATH

# Gphoto2 runtime environment

export CAMLIBS=$DIR/usr/lib/libgphoto2
export IOLIBS=$DIR/usr/lib/libgphoto2_port

# ImageMagick run-time environment

export MAGICK_CODER_MODULE_PATH=$DIR/usr/lib/modules-Q16HDRI/coders
export MAGICK_CODER_FILTER_PATH=$DIR/usr/lib/modules-Q16HDRI/filters

# QtWebEngine crash with some video card drivers
# https://github.com/qutebrowser/qutebrowser/issues/2368

export QT_XCB_FORCE_SOFTWARE_OPENGL=1
export QTWEBENGINE_CHROMIUM_FLAGS="--disable-gpu"

# Code to disable Plasma desktop detection with QDesktopService

export APPIMAGE_ORIGINAL_KDE_FULL_SESSION=$KDE_FULL_SESSION
export APPIMAGE_ORIGINAL_DESKTOP_SESSION=$DESKTOP_SESSION
export APPIMAGE_ORIGINAL_XDG_CURRENT_DESKTOP=$XDG_CURRENT_DESKTOP
export APPIMAGE_ORIGINAL_XDG_SESSION_DESKTOP=$XDG_SESSION_DESKTOP
#unset KDE_FULL_SESSION
#unset DESKTOP_SESSION
#unset XDG_CURRENT_DESKTOP
#unset XDG_SESSION_DESKTOP

# if no customized Qt debug loggin variable is set, turn on one for a better readability

if [ -z "$QT_MESSAGE_PATTERN" ] ; then

    export QT_MESSAGE_PATTERN="`echo -e "\033[34m%{function}\033[0m: %{message}"`"

fi

export APPIMAGE_STARTUP_LD_LIBRARY_PATH=$LD_LIBRARY_PATH
export APPIMAGE_STARTUP_QT_PLUGIN_PATH=$QT_PLUGIN_PATH
export APPIMAGE_STARTUP_XDG_DATA_DIRS=$XDG_DATA_DIRS
export APPIMAGE_STARTUP_PATH=$PATH

# See bug #401377: tested on Fedora 29 and Mageia 7 for transitional
# migration from openssl 1.0 to openssl 1.1

if [ -f /etc/pki/openssl10.cnf ] ; then

    export OPENSSL_CONF=/etc/pki/openssl10.cnf

fi

# See Bug #109060

if [ -f $DIR/usr/lib/libavif.so.13 ] ; then

    export LD_PRELOAD=$LD_PRELOAD:$DIR/usr/lib/libavif.so.13

fi

preload_shared_library libudev.so.0

# See bug #414737

preload_shared_library libxcb-dri3.so.0

# See bug #447150

preload_shared_library libcrypto.so.1.1
preload_shared_library libssl.so.1.1

# See bug #449308

preload_shared_library libnss3.so
preload_shared_library libnssutil3.so
preload_shared_library libsmime3.so

# See bug #451196 and #451780

preload_shared_library libgmodule-2.0.so.0

# See bug #216915 and #492040

if [[ ! (($OS_NAME == "manjarolinux"        && $OS_VERSION == "24.7")     ||
         ($OS_NAME == "openSUSE Tumbleweed" && $OS_VERSION -ge 20240908)) ]] ; then

    preload_shared_library libgnutls.so.30

fi

# See bug #261634

preload_shared_library libnettle.so.8

# See bug #461495
#
#preload_shared_library libpcre.so.3
#
#preload_shared_library libfontconfig.so.1
#preload_shared_library libfreetype.so.6

echo "-- Preloading shared libs: $LD_PRELOAD"

# Parse CLI options.

if   [[ $1 == "showfoto" ]] ; then

    # Run Showfoto as well.

    showfoto ${@:2}

elif [[ $1 == "debug" ]] ; then

    if   [[ $2 == "showfoto" ]] ; then

        # Showfoto in debug mode.

        echo "Starting Showfoto into GDB..."
        echo "Use 'bt' command on debugger prompt to get a crash backtrace."
        echo "Use 'q' command to quit debugger session."
        gdb -ex=r --args showfoto ${@:3}

    else

        # digiKam in debug mode.

        echo "Starting digiKam into GDB..."
        echo "Use 'bt' command on debugger prompt to get a crash backtrace."
        echo "Use 'q' command to quit debugger session."
        gdb -ex=r --args digikam ${@:2}

    fi

elif [[ $1 == "help" ]] ; then

    # digiKam/Showfoto CLI help.

    echo "digiKam AppImage bundle CLI options:"
    echo " without option       : run digiKam."
    echo " <showfoto>           : run Showfoto instead digiKam."
    echo " <debug>              : run digiKam into GDB."
    echo " <debug> <showfoto>   : run Showfoto into GDB."
    echo " <help>               : show these information."

else

    # Run digiKam as well.

    digikam $@

fi
