#!/bin/sh

PATH=/sbin:/usr/sbin:/bin:/usr/bin

# shut down any graphical boot that might exist
if [ -x /usr/bin/rhgb-client ]; then
    /usr/bin/rhgb-client --quit
fi

# We need to source this so that the login screens get translated
[ -f /etc/profile.d/lang.sh ] && . /etc/profile.d/lang.sh

# Run preferred X display manager
preferred=
if [ -f /etc/sysconfig/desktop ]; then
	. /etc/sysconfig/desktop
	if [ "$DISPLAYMANAGER" = GNOME ]; then
		preferred=/usr/sbin/gdm
	elif [ "$DISPLAYMANAGER" = KDE ]; then
		preferred=/usr/bin/kdm
	elif [ "$DISPLAYMANAGER" = XDM ]; then
	        preferred=/usr/bin/xdm
        elif [ -n "$DISPLAYMANAGER" ]; then
		preferred=$DISPLAYMANAGER
	fi
fi

shopt -s execfail

# If we're in early-login mode and something is running, bail out
if grep -q early-login /proc/cmdline 2> /dev/null ; then
	if [ -n "$preferred" ]; then
		pidof $preferred >/dev/null 2>&1 && exit 0
	fi
	pidof gdm-binary >/dev/null 2>&1 && exit 0
	pidof kdm >/dev/null 2>&1 && exit 0
	pidof xdm >/dev/null 2>&1 && exit 0
fi

if [ -n "$preferred" ]; then
	$preferred "$@" >/dev/null 2>&1
	if [ $? -ne 127 ]; then
		exec $0 "$@"
		exit $?
	fi
fi

# Fallbacks, in order
gdm "$@" >/dev/null 2>&1
if [ $? -ne 127 ]; then
	exec $0 "$@"
	exit $?
fi
kdm "$@" >/dev/null 2>&1
if [ $? -ne 127 ]; then
	exec $0 "$@"
	exit $?
fi
xdm "$@" >/dev/null 2>&1
if [ $? -ne 127 ]; then
	exec $0 "$@"
	exit $?
fi

# catch all exit error
exit 1