#!/bin/sh
set -eu

script_path=$0
while [ -L "$script_path" ]; do
  script_dir=$(CDPATH= cd -- "$(dirname -- "$script_path")" && pwd)
  link_target=$(readlink "$script_path")
  case "$link_target" in
    /*) script_path=$link_target ;;
    *) script_path=$script_dir/$link_target ;;
  esac
done
app_dir=$(CDPATH= cd -- "$(dirname -- "$script_path")" && pwd)
app_binary="$app_dir/netMail.bin"

show_error() {
  message=$1
  printf '%s\n' "$message" >&2
  if command -v zenity >/dev/null 2>&1; then
    zenity --error --title='netMail' --width=520 --text="$message" >/dev/null 2>&1 || true
  fi
}

if [ ! -x "$app_binary" ]; then
  show_error "Die netMail-Programmdatei fehlt: $app_binary"
  exit 126
fi

loader_report=$(
  LD_LIBRARY_PATH="$app_dir${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}" \
    ldd "$app_binary" "$app_dir/libsk4d.so" 2>&1 || true
)
if printf '%s\n' "$loader_report" | grep -Eq 'not found|version .* not found'; then
  missing=$(printf '%s\n' "$loader_report" | grep -E 'not found|version .* not found' | sort -u)
  show_error "netMail kann eine Linux-Laufzeitbibliothek nicht laden:

$missing

Ubuntu/Debian: Bitte das netMail-DEB-Paket verwenden oder install.sh erneut mit sudo starten."
  exit 127
fi

exec env LD_LIBRARY_PATH="$app_dir${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}" \
  "$app_binary" "$@"
