#!/bin/sh
# Connect+ launcher — picks a working Chromium sandbox mode automatically, and
# starts Connect+ again once, in safe graphics, if its GPU process ended it.
DIR="$(dirname "$(readlink -f "$0")")"
# A Wayland desktop that did not say so: started from somewhere without the
# session's XDG_SESSION_TYPE, the window stayed blank (Atlas, 2026-11-19).
if [ -z "$XDG_SESSION_TYPE" ] && [ -n "$WAYLAND_DISPLAY" ]; then
  export XDG_SESSION_TYPE=wayland
fi
FLAG=""
if [ -z "$SNAP" ] && [ -z "$FLATPAK_ID" ] && [ -z "$CONNECT_KEEP_SANDBOX" ]; then
  userns_ok=""
  if command -v unshare >/dev/null 2>&1; then
    unshare -Ur true 2>/dev/null && userns_ok=1
  elif [ "$(sysctl -n kernel.unprivileged_userns_clone 2>/dev/null)" != "0" ] && \
       [ "$(sysctl -n kernel.apparmor_restrict_unprivileged_userns 2>/dev/null)" != "1" ]; then
    userns_ok=1
  fi
  if [ -z "$userns_ok" ]; then
    sb="$DIR/chrome-sandbox"
    suid_ok=""
    if [ -u "$sb" ] && [ "$(stat -c %u "$sb" 2>/dev/null)" = "0" ]; then
      case ",$(findmnt -no OPTIONS -T "$DIR" 2>/dev/null | tr -d ' ')," in
        *,nosuid,*) ;;
        *) suid_ok=1 ;;
      esac
    fi
    [ -z "$suid_ok" ] && FLAG="--no-sandbox"
  fi
fi
MARK=""
[ -n "$XDG_RUNTIME_DIR" ] && MARK="$XDG_RUNTIME_DIR/connect-plus-gpu-restart"
[ -z "$MARK" ] && exec "$DIR/connect-plus.bin" $FLAG "$@"
"$DIR/connect-plus.bin" $FLAG "$@"
rc=$?
if [ "$rc" -ne 0 ] && [ -f "$MARK" ]; then
  rm -f "$MARK"
  # The same switches again, without the links or files the run was given.
  end=""
  for a do
    shift
    [ -n "$end" ] && continue
    case "$a" in
      --) end=1 ;;
      --*) set -- "$@" "$a" ;;
    esac
  done
  exec "$DIR/connect-plus.bin" $FLAG "$@"
fi
exit "$rc"
