## DBus session handling strategy from:
## http://www.linuxfromscratch.org/hints/downloads/files/starting-and-stopping-dbus-with-kdm.txt

retcode=0;

if [ -d $HOME ]; then
    # See whether dbus-daemon is already running.
    # dbus-daemon needs to be started by the user (UID) logging in.
    # Only start a dbus session if .dbus-session file is not found
    # in user's home directory.
    if [ -f $HOME/.dbus-session ]; then
        # Check if dbus-daemon for this user is running with pid
        # found in ~/.dbus-session
        DBUS_PS_PID=$(ps aux | grep -m 1 -E "^$USER.*dbus-daemon.*session.*" \
            | grep -v "grep" | sed 's@[[:space:]][[:space:]]*@ @g' | cut -d " " -f 2)
        
        # Read the pid from the .dbus-session file
        . $HOME/.dbus-session

        # .dbus-session might be stale 
        if [ -z "$DBUS_PS_PID" ]; then
            rm $HOME/.dbus-session
            
        # Check if they are the same   
        elif [ $DBUS_SESSION_BUS_PID -ne $DBUS_PS_PID ]; then
            kill -TERM $DBUS_PS_PID
            rm $HOME/.dbus-session
        fi
    fi
    
    if [ ! -f $HOME/.dbus-session ]; then
        dbus-launch --auto-syntax > $HOME/.dbus-session
        retcode=$?
    fi
fi

if [ $retcode -ne 0 ]; then
    echo "Error launching dbus ($retcode)."
fi

return $retcode
