#!/bin/bash
# Disable keyring prompts
export GNOME_KEYRING_CONTROL=""

# Prefer Wayland when available so touch long-press produces right-click (context menu)
# like the rest of the desktop. X11/XWayland does not get that behavior for Chromium.
USE_WAYLAND=0
if [ -n "$WAYLAND_DISPLAY" ] && [ -S "${XDG_RUNTIME_DIR:-/run/user/$(id -u)}/$WAYLAND_DISPLAY" ]; then
  USE_WAYLAND=1
fi

if [ "$USE_WAYLAND" -eq 1 ]; then
  # Native Wayland: fullscreen + touch-friendly (long-press = right-click)
  export GDK_BACKEND=wayland
  # Wait for compositor
  for i in {1..60}; do
    if [ -S "${XDG_RUNTIME_DIR:-/run/user/$(id -u)}/$WAYLAND_DISPLAY" ]; then
      pgrep -x labwc >/dev/null 2>&1 && break
    fi
    sleep 0.5
  done
  sleep 3
  /usr/bin/chromium --start-fullscreen --noerrdialogs --disable-infobars --disable-session-crashed-bubble --disable-restore-session-state --no-first-run --password-store=basic --use-mock-keychain --ozone-platform=wayland --enable-features=WaylandWindowDecorations --disable-features=UseChromeOSDirectVideoDecoder --app=http://127.0.0.1:8080 &
else
  # Fallback: X11 (e.g. no Wayland session)
  export DISPLAY=:0
  export GDK_BACKEND=x11
  unset WAYLAND_DISPLAY
  for i in {1..60}; do
    if xset q >/dev/null 2>&1 || [ -n "$DISPLAY" ]; then
      if pgrep -x pcmanfm >/dev/null 2>&1 || pgrep -x lxsession >/dev/null 2>&1 || pgrep -x xfdesktop >/dev/null 2>&1; then
        break
      fi
    fi
    sleep 0.5
  done
  sleep 5
  /usr/bin/chromium --start-fullscreen --noerrdialogs --disable-infobars --disable-session-crashed-bubble --disable-restore-session-state --no-first-run --password-store=basic --use-mock-keychain --ozone-platform=x11 --disable-features=UseChromeOSDirectVideoDecoder --app=http://127.0.0.1:8080 &
  sleep 3
  for i in {1..10}; do
    WINDOW_ID=$(wmctrl -l 2>/dev/null | grep -i chromium | head -1 | awk '{print $1}')
    if [ -n "$WINDOW_ID" ]; then
      wmctrl -i -r "$WINDOW_ID" -b add,fullscreen 2>/dev/null
      break
    fi
    sleep 0.5
  done
fi



# Keep script running
wait

# Kiosk mode (commented out - uncomment to use instead of fullscreen)
# /usr/bin/chromium --kiosk --noerrdialogs --disable-infobars --disable-session-crashed-bubble --disable-restore-session-state --no-first-run --password-store=basic --use-mock-keychain --ozone-platform=x11 --app=http://127.0.0.1:8080
