#!/usr/bin/env bash

# if /proc/version contains "microsoft-standard-WSL2", then we are running in WSL2
if grep -q "microsoft-standard-WSL2" /proc/version; then
  # fix for missing icons in taskbar
  export GDK_BACKEND=x11
fi

# WebKitGTK 6.0 uses bubblewrap (bwrap) for sandboxing, which requires
# unprivileged user namespaces. Disable the sandbox if they are unavailable.
can_use_userns() {
  # Debian/Ubuntu-specific sysctl
  if [ -f /proc/sys/kernel/unprivileged_userns_clone ] && [ "$(cat /proc/sys/kernel/unprivileged_userns_clone)" = "0" ]; then
    return 1
  fi
  # General: max_user_namespaces set to 0
  if [ -f /proc/sys/user/max_user_namespaces ] && [ "$(cat /proc/sys/user/max_user_namespaces)" = "0" ]; then
    return 1
  fi
  # Quick functional check
  if command -v bwrap > /dev/null 2>&1; then
    if ! bwrap --ro-bind / / --dev /dev --proc /proc true 2>/dev/null; then
      return 1
    fi
  fi
  return 0
}

# check if libwebkitgtk-6.0 or libwebkit2gtk-4.0 is installed
if /sbin/ldconfig -p | grep libwebkitgtk-6.0 > /dev/null; then
  if ! can_use_userns; then
    export WEBKIT_DISABLE_SANDBOX_THIS_IS_DANGEROUS=1
  fi
  /usr/share/speedifyui/speedify_ui_webkit60 "$@"
elif /sbin/ldconfig -p | grep libwebkit2gtk-4.0 > /dev/null; then
  /usr/share/speedifyui/speedify_ui_webkit40 "$@"
else
  echo "ERROR: libwebkitgtk-6.0 or libwebkit2gtk-4.0 is required to run the UI"
  exit 1
fi
