#!/usr/bin/env bash

# The purpose of this custom AppRun script is to allow the user to specify
# which binary from the multi-binary AppImage to run. This can be done in
# one of two ways:
# - The binary name can be specified as the first command line argument.
# If there is a binary with that name inside the AppImage, it will be run
# instead of the default one.
# - The user can create a symlink to the AppImage file and run it via the
# symlink. If inside the AppImage there is a binary with a name that matches
# the symlink name, it will be launched instead of the default one.

HERE="$(dirname "$(readlink -f "${0}")")"

source "$HERE"/apprun-hooks/"linuxdeploy-plugin-gtk.sh"

export CAMLIBS=$HERE/usr/lib/libgphoto2/`ls -1 --group-directories-first $HERE/usr/lib/libgphoto2|head -1`

export IOLIBS=$HERE/usr/lib/libgphoto2_port/`ls -1 --group-directories-first $HERE/usr/lib/libgphoto2_port|head -1`

export GIO_EXTRA_MODULES=$HERE/usr/lib/gio/modules

if [[ ! -z $APPIMAGE ]] ; then
  BINARY_NAME=$(basename "$ARGV0")
  if [[ ! -z "$1" ]] && [[ -e "$HERE/usr/bin/$1" ]] ; then
    EXECFILE="$HERE/usr/bin/$1" ; shift
  elif [[ -e "$HERE/usr/bin/$BINARY_NAME" ]] ; then
    EXECFILE="$HERE/usr/bin/$BINARY_NAME"
  else
    EXECFILE="$HERE/usr/bin/darktable"
  fi
else
  EXECFILE="$HERE/usr/bin/darktable"
fi

exec "$EXECFILE" "$@"
