#!/bin/bash --login
#
# Copyright (C) 2021  Igor Vlasenko <viy@altlinux.org>
#
# wayland session wrapper script.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.
#

# let user deifine his own wrapper
test -x ~/.wayland-sessions-wrapper && exec ~/.wayland-sessions-wrapper "$@"

PROG="${0##*/}"

SourceIfNotEmpty()
{
	local f="$1"
	shift
	[ -s "$f" ] && . "$f" "$@"
}

# redirect stderr to a file, if it is not yet redirected by DM
if [ -z "$GDMSESSION" -a -d /proc/self -a -c /proc/self/fd/2 ]; then
	for errfile in "$HOME/.local/share/wayland-session.log"; do
		if install -m600 /dev/null "$errfile" 2>/dev/null; then
			exec &>"$errfile"
			break
		fi
	done
fi

if [ $# -eq 0 ]; then
	echo "$PROG: command argument is required"
	echo "Usage: $PROG <command>"
	exit 1
fi

echo "Running $PROG[$$] $*"

# force it here for some old DM
XDG_SESSION_TYPE=${XDG_SESSION_TYPE:-wayland}

case "$1" in
	/usr/bin/fbcon|fbcon|/usr/bin/fbterm|fbterm|/usr/bin/kmscon|kmscon)
		XDG_SESSION_TYPE=tty
		;;
esac
export XDG_SESSION_TYPE

WRAPPER_DIR=/etc/dm-sessions/wayland

# Source shell scripts from system $WRAPPER_DIR/profile.d/
for f in $WRAPPER_DIR/profile.d/*.sh; do
	# Don't run *.rpm* and *~ scripts
	[ "${f%.rpm*}" = "$f" -a "${f%\~}" = "$f" ] || continue

	SourceIfNotEmpty "$f" "$@"
done

unset f

# https://lists.altlinux.org/pipermail/devel/2021-December/216070.html
[ "$XDG_SESSION_TYPE" = "wayland" ] && \
	SourceIfNotEmpty /etc/X11/profile.d/ssh-agent.sh

# Beware that Wayland servier is not available yet.
# put some some hardware user settings in init.d
for f in $WRAPPER_DIR/init.d/*; do
	# Don't run *.rpm* and *~ scripts
	[ "${f%.rpm*}" = "$f" -a "${f%\~}" = "$f" ] || continue

	if [ -x "$f" ]; then
		"$f" &
	fi
done

unset f

# TODO: SELinux wrapper
SELINUX_WRAPPER=

DBUS_WRAPPER=
# we already have user's dbus session or we are about to run it
[ -n "$DBUS_SESSION_BUS_ADDRESS" -o "$1" = "dbus-run-session" ] || DBUS_WRAPPER=dbus-run-session

exec $DBUS_WRAPPER $SELINUX_WRAPPER "$@"

# Local Variables:
# mode: sh
# tab-width: 8
# indent-tabs-mode: t
# sh-basic-offset: 8
# End:
