#!/bin/bash

###############################################
## x session for instantOS, use with lightdm ##
###############################################

# used for shutdown

# try to obtain a temp dir unique to the user, to enable
# instantOS xsessions for concurrent users on the same machine
RTD="$(instantruntimedir)"

if [ -z "$RTD" ]; then
	mkdir -p /tmp/instantos
	RTD="/tmp/instantos"
fi

echo $$ >"${RTD}"/instantosrunning

# just in case, some systems might not do this
cd || echo "failed to access home directory"

# execute autostart even if instantautostart doesn't work
if ! command -v instantautostart &>/dev/null; then
	sleep 4
	bash ~/.instantautostart
fi &

# needed to fix some misbehaving applications
if iconf wmname; then
	wmname "$(iconf wmname)"
fi

[ -e ~/.instantsession ] && source ~/.instantsession

ILOGFILE="$HOME/.local/share/instantos.log"

if iconf -i debug; then
	export INSTANTDEBUG="true"
fi

if [ -z "$INSTANTDEBUG" ]; then
	if [ -e "$ILOGFILE" ] && [ "$(du -sm "$ILOGFILE" | grep -o '^[0-9]*')" -gt 20 ]; then
		echo "log file has gotten out of hand, clearing logs"
		echo "start of log file" >"$ILOGFILE"
	fi
fi

# loop so crashing instantwm doesn't end the x session
while [ -e "${RTD}"/instantosrunning ]; do
	# allow changing wm on the fly
	if [ -e "${RTD}"/wmoverride ]; then
		if command -v "$(cat "${RTD}"/wmoverride)" &>/dev/null; then
			"$(cat ${RTD}/wmoverride)" 2>~/.instantos.log &
			WMPID="$!"
			echo "$WMPID" >"${RTD}"/wmpid
			while kill -0 "$WMPID"; do
				sleep 1
			done
		fi
		rm "${RTD}"/wmoverride
	else
		# Log stderror or stdout to a file
		if ! [ -e .local/share ]; then
			mkdir -p ~/.local/share
		fi

		export XDG_CURRENT_DESKTOP="instantwm"

		if [ -n "$INSTANTDEBUG" ]; then
			instantwm &>>~/.local/share/instantos.log
			export WMEXITCODE="$?"
		else
			instantwm 2>>~/.local/share/instantos.log
			export WMEXITCODE="$?"
		fi
	fi
	echo "$(date): window manager was restarted or crashed" >>"$ILOGFILE"
	echo "window manager exit code: $WMEXITCODE" >>"$ILOGFILE"
done
