#!/bin/bash

# first get helper functions (e.g. DEBUG, load_scheme, ...)
. "${0%/*}/helper_functions"
. "${SCRIPT_DIR}/x_helper_functions"

# is there something to save context for winowmaker?
wmaker_term() {
	killall -TERM wmaker
	return 0
}

# this is to save GNOME context
save_gnome_session(){
    get_x_user
    DEBUG "Save GNOME session for user: $X_USER" INFO
    [ -n "$X_USER" -a -n "$DISP" ] && su $X_USER -s /bin/bash -c "DISPLAY=$DISP /opt/gnome/bin/gnome-session-save"
    [ $? != "0" ] && DEBUG "Could not log out user '$X_USER' out of GNOME display '$DISP'." DIAG
}

kde_shutdown() {
    DEBUG "process function: kde_shutdown" DEBUG

    get_x_user
    DEBUG "Shutting down kde for user: $X_USER" INFO
    [ -n "$X_USER" -a -n "$DISP" ] && su $X_USER -s /bin/bash -c "DISPLAY=$DISP /opt/kde3/bin/dcop ksmserver ksmserver logout 0 2 2"
    if [ $? != "0" ]; then
        DEBUG "Could not shut down KDE for user '$X_USER'." DIAG
        return 1;
    fi
    return 0
}

# just try to shutdown all windowmanagers
# until success
kde_shutdown
ret="$?"
if [ $ret != 0 ]; then
    wmaker_term
    save_gnome_session
    #shutdown anyways
    shutdown -h now
    ret="$?"
fi

$SCRIPT_RETURN $EV_ID $ret "wm_shutdown finished"
EXIT $ret
