#!/bin/ash

# allow applications running as spot to talk to dwl
SPOT_RUNTIME_DIR=`run-as-spot sh -c 'mkdir -p $XDG_RUNTIME_DIR && echo $XDG_RUNTIME_DIR'`
for F in $WAYLAND_DISPLAY $WAYLAND_DISPLAY.lock; do
	umount -l $SPOT_RUNTIME_DIR/$F 2>/dev/null
	touch $SPOT_RUNTIME_DIR/$F
	chown spot:spot $XDG_RUNTIME_DIR/$F
	mount --bind $XDG_RUNTIME_DIR/$F $SPOT_RUNTIME_DIR/$F
done

[ "$GDK_BACKEND" = "x11" ] && export DISPLAY=:0

# https://gitlab.freedesktop.org/wlroots/wlroots/-/blob/master/docs/env_vars.md
# screen artifacts in the wlroots environment may improve by using the
# legacy DRM interface instead of atomic mode setting (uncomment next line)
#export WLR_DRM_NO_ATOMIC=1

echo "add $DISPLAY . `mcookie`" | xauth -q -f ~/.Xauthority
cp -f ~/.Xauthority /home/spot/.Xauthority
chown spot:spot /home/spot/.Xauthority

if [ "$GDK_BACKEND" = "x11" ]; then
	Xwayland-spot $DISPLAY &

	MAX=100
	CT=0
	while ! xdpyinfo >/dev/null 2>&1; do
		sleep 0.1
		CT=$(( CT + 1 ))
		if [ "$CT" -ge "$MAX" ]; then
			echo "FATAL: $0: Gave up waiting for X server $DISPLAY"
			exit 11
		fi
	done
fi

# desktop settings
[ -e "$XDG_CONFIG_HOME/wmonitors/wmon_cmd" ] && . $XDG_CONFIG_HOME/wmonitors/wmon_cmd

. /etc/rc.d/wl_func
apply_gtk_settings

# pass environment variables to D-Bus activated applications like Blueman
dbus-update-activation-environment WAYLAND_DISPLAY DISPLAY
run-as-spot dbus-update-activation-environment WAYLAND_DISPLAY DISPLAY

if [ "$GDK_BACKEND" = "x11" ]; then
	gsettings set org.gnome.desktop.wm.preferences button-layout "appmenu:maximize,close"
	run-as-spot gsettings set org.gnome.desktop.wm.preferences button-layout "appmenu:maximize,close"
	if [ "$XDG_SESSION_TYPE" != "wayland" ]; then
		clean_desk_icons
		fixPuppyPin ~/Choices/ROX-Filer/PuppyPin
		roxfiler -p ~/Choices/ROX-Filer/PuppyPin
		#CURRENTBG="`cat $HOME/.config/wallpaper/bg_img 2>/dev/null`"
		#[ -z "$CURRENTBG" ] && CURRENTBG="`ls -1 /usr/share/backgrounds/default.* | head -n 1`"
		#set_bg "$CURRENTBG" &
		/sbin/pup_event_frontend_d &
	fi
else
	gsettings set org.gnome.desktop.wm.preferences button-layout "appmenu"
	run-as-spot gsettings set org.gnome.desktop.wm.preferences button-layout "appmenu"
	xdg_autostart.sh
fi
/usr/sbin/delayedrun &

if [ "$GDK_BACKEND" = "x11" ]; then
	CURRENTWM="`cat /etc/windowmanager 2>/dev/null`"
	[ -z "$CURRENTWM" -o -z "`command -v $CURRENTWM`" ] && CURRENTWM="jwm"
	$CURRENTWM &
else
	exec dwl-send /tmp/dwl.socket
fi
