#!/bin/sh
set -eu

resolve_link() {
  target=$1
  while [ -L "$target" ]; do
    link=$(readlink "$target")
    case "$link" in
      /*) target=$link ;;
      *) target=$(dirname "$target")/$link ;;
    esac
  done
  printf '%s\n' "$target"
}

script_path=$(resolve_link "$0")
script_dir=$(CDPATH= cd -- "$(dirname -- "$script_path")" && pwd)

app_root=${PHOTONFILE_DESKTOP_APP_ROOT:-}
if [ -z "$app_root" ]; then
  for candidate in \
    "$script_dir/../lib64/photonfile" \
    "$script_dir/../lib64/photonfile" \
    "$script_dir/../lib/photonfile" \
    "/usr/lib64/photonfile"; do
    if [ -x "$candidate/bin/photonfile_desktop" ]; then
      app_root=$candidate
      break
    fi
  done
fi

if [ -z "$app_root" ] || [ ! -x "$app_root/bin/photonfile_desktop" ]; then
  echo "PhotonFile runtime was not found." >&2
  exit 127
fi

export LD_LIBRARY_PATH="$app_root/lib${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"
export QT_PLUGIN_PATH="$app_root/plugins${QT_PLUGIN_PATH:+:$QT_PLUGIN_PATH}"
export QML2_IMPORT_PATH="$app_root/qml${QML2_IMPORT_PATH:+:$QML2_IMPORT_PATH}"
export QML_IMPORT_PATH="$app_root/qml${QML_IMPORT_PATH:+:$QML_IMPORT_PATH}"

if [ -z "${FONTCONFIG_FILE:-}" ] && [ -f "$app_root/share/fontconfig/fonts.conf" ]; then
  export FONTCONFIG_FILE="$app_root/share/fontconfig/fonts.conf"
fi

exec "$app_root/bin/photonfile_desktop" "$@"
