#!/bin/bash
set -e
OUTER_DISPLAY="${DISPLAY:-:50}"

# Cinnamon's Display panel writes ~/.config/cinnamon-monitors.xml (NOT the
# GNOME-style ~/.config/monitors.xml -- libcinnamon-desktop's CinnamonRRConfig
# renamed it). Read the Cinnamon file first, fall back to the GNOME one.
MONITORS_XML=""
for f in "$HOME/.config/cinnamon-monitors.xml" "$HOME/.config/monitors.xml"; do
	[ -r "$f" ] && { MONITORS_XML="$f"; break; }
done
GEOM=""
if [ -n "$MONITORS_XML" ]; then
	W=$(grep -m1 -o '<width>[0-9]*</width>' "$MONITORS_XML" | grep -o '[0-9]*')
	H=$(grep -m1 -o '<height>[0-9]*</height>' "$MONITORS_XML" | grep -o '[0-9]*')
	[ -n "$W" ] && [ -n "$H" ] && GEOM="${W}x${H}"
fi
if [ -z "$GEOM" ]; then
	GEOM=$(DISPLAY="$OUTER_DISPLAY" xdpyinfo 2>/dev/null | awk '/dimensions:/{print $2}')
fi
[ -z "$GEOM" ] && GEOM="1280x800"

N=150
while [ -e "/tmp/.X11-unix/X$N" ]; do N=$((N + 1)); done

DISPLAY="$OUTER_DISPLAY" /usr/bin/Xephyr ":$N" -screen "$GEOM" -noreset -resizeable >/tmp/xephyr-cinnamon-$N.log 2>&1 &
XEPHYR_PID=$!
for i in $(seq 1 100); do
	DISPLAY=":$N" /usr/bin/xdpyinfo >/dev/null 2>&1 && break
	sleep 0.1
done
trap "kill $XEPHYR_PID 2>/dev/null" EXIT
export DISPLAY=":$N"

export LIBGL_ALWAYS_SOFTWARE=1
export CLUTTER_PAINT=disable-clipped-redraws

# Xephyr advertises 0Hz for every mode -> both Muffin's file restore and
# Cinnamon's Display "Apply" fail to persist a resolution (same as
# GNOME/Mutter). Re-assert the saved geometry ourselves via live xrandr
# once the shell is up; retry a few times in case csd-xrandr stomps it.
if [ -n "$W" ] && [ -n "$H" ]; then
	(
		for i in $(seq 1 150); do
			pgrep -x cinnamon >/dev/null 2>&1 && break
			pgrep -f '/usr/bin/cinnamon' >/dev/null 2>&1 && break
			sleep 0.2
		done
		for j in 1 2 3 4 5 6; do
			sleep 1
			cur=$(xrandr 2>/dev/null | awk '/\*/{print $1; exit}')
			[ "$cur" = "$GEOM" ] && break
			xrandr --output default --mode "$GEOM" 2>/dev/null || xrandr -s "$GEOM" 2>/dev/null
		done
	) &
fi

cinnamon-session --session cinnamon2d "$@" &
CINN_PID=$!
wait "$CINN_PID"
