#! /bin/bash
# Copyright (c) 1996-2002 SuSE Linux AG, Nuernberg, Germany.
# Copyright (c) 2014 SUSE LINUX Products GmbH, Nuernberg, Germany.
# All rights reserved.
#
# Author: Florian La Roche, 1996
#	  Werner Fink <werner@suse.de>, 1996,98,99,2014
#         Martin Scherbaum, 1997
#         Reinhard Max <max@suse.de>, 1997
#
# Please send feedback to http://www.suse.de/feedback
#
# /usr/lib/X11/display-manager
#

DEFAULT_WM="default"

. /etc/sysconfig/displaymanager
. /etc/sysconfig/language
test -f /etc/sysconfig/windowmanager && . /etc/sysconfig/windowmanager
if [ -r /etc/profile.d/desktop-data.sh ]; then
    . /etc/profile.d/desktop-data.sh
elif [ -r /usr/etc/profile.d/desktop-data.sh ]; then
    . /usr/etc/profile.d/desktop-data.sh
fi

locale_vars="     \
LANG              \
LC_CTYPE          \
LC_NUMERIC        \
LC_TIME           \
LC_COLLATE        \
LC_MONETARY       \
LC_MESSAGES       \
LC_PAPER          \
LC_NAME           \
LC_ADDRESS        \
LC_TELEPHONE      \
LC_MEASUREMENT    \
LC_IDENTIFICATION \
LC_ALL"

unset LC_ALL
for lc in $locale_vars
do
    eval val="\$RC_$lc"
    if test -n "$val"; then
        eval $lc="\$RC_$lc"
        export $lc
    fi
done
unset lc val

if test -z "$WINDOWMANAGER" -a -n "$DEFAULT_WM" ; then
    SAVEPATH=$PATH
    PATH=$PATH:/usr/X11R6/bin:/usr/openwin/bin
    desktop=/usr/share/xsessions/${DEFAULT_WM}.desktop
    if test -s "$desktop" ; then
        while read -r line; do
            case ${line} in
            Exec=*) WINDOWMANAGER="$(command -v ${line#Exec=})"
                    break
            esac
        done < $desktop
    fi
    if test -n "$DEFAULT_WM" -a -z "$WINDOWMANAGER" ; then
        WINDOWMANAGER="$(command -v ${DEFAULT_WM##*/})"
    fi
    PATH=$SAVEPATH
    unset SAVEPATH desktop
fi
unset DEFAULT_WM
export WINDOWMANAGER

DMDIR=/usr/etc/X11/xdm
RELOADSIGNAL="-HUP"

PIDFILELNK="/run/displaymanager.pid"


xdm_reload_files () {
    if [ -x $DMIR/SuSEconfig.xdm ]; then
        # Do no try to start Xserver on platforms which may ship without
        # graphics card (bsc#1039497)
        if [ "$(arch)" == "aarch64" -o "$(arch)" == "ppc64le" ]; then
            if ! [ -c /dev/fb* -o -d /dev/dri ]; then
                sed -i -e "s+DISPLAYMANAGER_STARTS_XSERVER=.*+DISPLAYMANAGER_STARTS_XSERVER=\"no\"+g" \
                          /etc/sysconfig/displaymanager
            else
                sed -i -e "s+DISPLAYMANAGER_STARTS_XSERVER=.*+DISPLAYMANAGER_STARTS_XSERVER=\"yes\"+g" \
                          /etc/sysconfig/displaymanager
            fi
        fi
        MD5DIR="/var/adm/SuSEconfig/md5" \
        $DMDIR/SuSEconfig.xdm | \
        sed 's+\(.*\)+/usr/lib/X11/display-manager: \1+g' | \
        /bin/logger
	return 0
    fi
}

splashcopy()
{
    local from=$1
    local to=$2
    if [ "$SPLASH" = yes ]
    then
	ver=$(sed "s/.*v\([[:digit:]]\)\.\([[:digit:]]\).*/\\1\\2/" /proc/splash)
	if [ $ver -gt 31 ]
	then
	    echo "copy $from $to" > /proc/splash
	    echo "@$to silent" > /proc/splash
	    echo "@$to show -1" > /proc/splash
	fi
    fi
}

plymouth_quit()
{
    if [ -x /usr/bin/plymouth ]; then
        plymouth quit
        plymouth --wait
    fi
}

#set -x

# DISPLAYMANAGER used to be set in /etc/sysconfig/displaymanager, but the default is now set by update-alternatives
DISPLAYMANAGER=$(realpath --relative-base=/usr/lib/X11/displaymanagers /usr/lib/X11/displaymanagers/default-displaymanager)
DM=${DISPLAYMANAGER##*/}

case "$DM" in
    console)	
	plymouth_quit
	exit 0
	;;
    *)
	test -d /etc/X11/xdm || mkdir -p /etc/X11/xdm
	# SUSEconfig.xdm edits these files appropriate to /etc/sysconfig/displaymanager
	test -r /etc/X11/xdm/xdm-config   || cp $DMDIR/xdm-config /etc/X11/xdm/xdm-config
	test -r /etc/X11/xdm/Xservers     || cp $DMDIR/Xservers   /etc/X11/xdm/Xservers
	# still often sourced by old ~/.xinitrc or ~/.xsession user files ...
	test -d /etc/X11/xinit || mkdir -p /etc/X11/xinit
	test -r /etc/X11/xinit/xinitrc.common || ln -snf /usr/etc/X11/xinit/xinitrc.common /etc/X11/xinit/xinitrc.common
	for i in  /usr/lib/X11/displaymanagers/*
	do
	    tmp=${i%.fallback} 
	    test "$tmp" != "$i" -a -e $tmp && continue # pick foodm over foodm.fallback
	    DISPLAY_MANAGERS="$DISPLAY_MANAGERS ${tmp##*/}"
	    . $i
	done
	for i in $DISPLAY_MANAGERS
	do
	    name="${i}_vars"
	    type -t $name &> /dev/null || continue
	    PIDFILE=/run/$i.pid
	    $name $DM && break
	done
	if [ -z "$DISPLAYMANAGER" -o ! -x "$DISPLAYMANAGER" ]
	then
	    PIDFILE=/run/xdm.pid
	    xdm_vars xdm  # FALLBACK
	fi
	unset i
	;;
esac

DM=${DISPLAYMANAGER##*/}

case "$1" in
    start)

	# use system keyboard as global X keyboard configuration
	if [ -x $DMDIR/keytable ]; then
	   $DMDIR/keytable
        fi

	[ -n "$STARTPROC" ] && $STARTPROC
	echo -n "Starting service $DM"
	# Graphical failsafe mode (Bug #246158).
	#
	# Needs changes in kernel commandline of "Failsafe" entry in
	# /boot/grub/menu.lst.
	#
	#  * use the same "vga" option value as in the non-"Failsafe" entry
	#  * remove "3" option (runlevel)
	#  * add "x11failsafe" option
	if cat /proc/cmdline | grep -q x11failsafe; then
            if [ -f /etc/X11/xorg.conf.install ]; then
		export XORGCONFIG=xorg.conf.install
                echo
                echo "Using failsafe X.Org configuration /etc/X11/xorg.conf.install"
            else
                echo
                echo "The failsafe X.Org configuration /etc/X11/xorg.conf.install no longer exists."
                echo "Either move it back (if still available) or remove \"x11failsafe\" from your"
                echo "kernel commandline to use the native graphics driver instead of the failsafe"
                echo "graphics driver. Of course the latter option no longer can be called failsafe."
                exit 6
            fi
	fi
	if ! startproc -p $PIDFILE $DISPLAYMANAGER $XDMOPTIONS; then
	    # After a crash or a kill signal we may have
	    # a wrong ownership of /dev/xconsole
	    if test -x $DMDIR/TakeDevices ; then
		$DMDIR/TakeDevices
	    else
		chown root:tty /dev/xconsole /dev/tty0
		chmod 622      /dev/xconsole /dev/tty0
	    fi
	    exit 1
	fi
	# when started up successfuly, use DMs PID file as ours
	ln -snf $PIDFILE $PIDFILELNK
	;;
    reload|force-reload)
	echo -n "Reload service $DM"
	[ -n "$RELOADPROC" ] && $RELOADPROC
	# $MAINPID is exported by systemd
	kill $RELOADSIGNAL $MAINPID
	;;
    *)
	echo "Usage: $0 {start|reload|force-reload}"
	exit 1
esac
