if [ -n "${X2GO_SESSION:-}" ]; then
    x2go_session_display_geometry=$(perl -F, -ane 'for (@F) { /^geometry=(.*)$/ && print $1 }' \
	"~/.x2go/C-${X2GO_SESSION}/options")

    if [ -n "${x2go_session_display_geometry}" ]; then
        xrandr --output default --mode "${x2go_session_display_geometry}"
    fi
fi

if jq -e '.user.user_roles | any(. == "admin")' \
  "$PUAVO_SESSION_PATH" >/dev/null; then
    export PUAVO_PERSISTENT_DISPLAY_MANAGEMENT=true
fi

export MUTTER_MONITOR_FILENAME="monitors-$(hostname).xml"

if [ "$(puavo-conf puavo.displays.forced)" = 'true' ]; then
  gdm_monitors_xml_path='/var/lib/gdm3/.config/monitors.xml'
  monitors_xml_path=~/".config/${MUTTER_MONITOR_FILENAME}"
  if [ -e "$gdm_monitors_xml_path" ]; then
    cp "$gdm_monitors_xml_path" "$monitors_xml_path"
  else
    rm -f "$monitors_xml_path"
  fi
fi

MUTTER_ALLOW_CONFIGURATION="$(puavo-conf puavo.xrandr.mutter_permissions)"
if [ "$MUTTER_ALLOW_CONFIGURATION" = 'auto' ]; then
  if [ '(' -n "$(puavo-conf puavo.xrandr.args | jq -r '.[]')" \
              -o -n "$(puavo-conf puavo.xrandr.apply_presets)" ')' \
        -a "$(jq '.monitors_xml != null' /etc/puavo/device.json)" != 'true' ]; then
    if [ "$(puavo-conf puavo.xrandr.forced)" = 'true' ]; then
      MUTTER_ALLOW_CONFIGURATION=temporary
    else
      MUTTER_ALLOW_CONFIGURATION=temporary,user
    fi
  else
    MUTTER_ALLOW_CONFIGURATION=default,temporary,user
  fi
fi
export MUTTER_ALLOW_CONFIGURATION

/usr/lib/puavo-desktop/run-xrandr
