#!/bin/sh

FMRI='svc:/application/x11/x11-server'
PROP='options/server'
DTLOGIN=/etc/rc2.d/S99dtlogin
SAVED=/etc/rc2.d/_S99dtlogin.saved
PKG_XWPL=SUNWxwplr	# X Window System platform software configuration

# go to console only (not logged at /var/svc/log/)
exec < /dev/console > /dev/console 2>&1

disable_dtlogin() {
    if [ -f $DTLOGIN -a ! -f $SAVED ]; then
	mv $DTLOGIN $SAVED
	echo "echo \"Notice: \$0 disabled by $0\"" > $DTLOGIN
	chmod 544 $DTLOGIN
	echo "Notice: $DTLOGIN is disabled"
    fi
}

restore_dtlogin() {
    if [ -f $SAVED ]; then
	mv $SAVED $DTLOGIN
	echo "Notice: $DTLOGIN is restored"
    fi
}

do_check() {
    # step 1: check property existnece
    if svcprop -q -p $PROP $FMRI; then
	# exists -> go on checking
	:
    elif pkginfo $PKG_XWPL > /dev/null 2>&1; then
	# should exist but not found
	echo; echo "Error: $0: cannot retrieve service property ($FMRI/:property/$PROP).  Reinstallation recommended."
	exit 1
    else
	# doesn't exist because SUNWxwplr isn't installed -> OK
	exit 0
    fi

    # step 2: check X server configuration
    xserver=`svcprop -p $PROP $FMRI`
    case "$xserver" in
	/usr/openwin/bin/Xsun)
	    config=/etc/openwin/server/etc/OWconfig ;;
	*/Xsun)
	    echo; echo "Warning: $0: assuming X server '$xserver' as Xsun"
	    config=/etc/openwin/server/etc/OWconfig ;;
	/usr/X11/bin/Xorg)
	    config=/etc/X11/xorg.conf ;;
	*/Xorg)
	    echo; echo "Warning: $0: assuming X server '$xserver' as Xorg"
	    config=/etc/X11/xorg.conf ;;
	*)
	    # Xserver is unknown to us
	    echo; echo "Error: $0: cannot figure out X server: $xserver"
	    exit 1 ;;
    esac

    if [ -x "$xserver" ]; then
	if [ -f "$config" ]; then
	    # X server seems ready to run
	    restore_dtlogin
	else
	    echo
	    echo "Warning: X server ($xserver) requires configuration file ($config) but not found."
	    echo "Run 'kdmconfig' and/or 'Xorg -configure' to create it."
	    disable_dtlogin
	fi
    else
	echo
	echo "Warning: Xserver ($xserver) is being selected but not found."
	echo " Redo installation or add X server package(s) manually."
	disable_dtlogin
    fi
}

case "$1" in
    start)
	do_check ;;
    *)
	;;
esac
