#!/bin/bash
#
# Invoke the "appropriate" directory viewer
#

# First, the preferred file manager for softWoRx (for either KDE or Gnome)
# is dolphin. Just use that if it's there
#if [ -e /usr/bin/dolphin ]; then
#    /usr/bin/dolphin $1 >& /dev/null &
#    sleep 1
#    exit 1
#fi

#
# Otherwise, try to determine whether KDE or Gnome is running
# and use their file manager tools
#
is_kde=0
is_gnome=0

if [ -n "$DESKTOP_SESSION" ]; then
    echo $DESKTOP_SESSION | fgrep -iq kde
    if [ $? -eq 0 ]; then
        # echo "Found KDE from DESKTOP_SESSION"
        is_kde=1
    else
        echo $DESKTOP_SESSION | fgrep -iq gnome
        if [ $? -eq 0 ]; then
            # echo "Found GNOME from DESKTOP_SESSION"
            is_gnome=1
        fi
    fi
fi

if [ $is_kde -eq 0 ] && [ $is_gnome -eq 0 ]; then
    if [ -n "$XDG_CURRENT_DESKTOP" ]; then
        echo $XDG_CURRENT_DESKTOP | fgrep -iq kde
        if [ $? -eq 0 ]; then
            # echo "Found KDE from XDG_CURRENT_DESKTOP"
            is_kde=1
        else
            echo $XDG_CURRENT_DESKTOP | fgrep -iq gnome
            if [ $? -eq 0 ]; then
                # echo "Found GNOME from XDG_CURRENT_DESKTOP"
                is_gnome=1
            fi
        fi
    fi
fi

# if we still haven't found anything...
if [ $is_kde -eq 0 ] && [ $is_gnome -eq 0 ]; then
    fgrep -iq kde /etc/sysconfig/desktop
    if [ $? -eq 0 ]; then
        # echo "Found KDE from /etc/sysconfig/desktop"
        is_kde=1
    else
        fgrep -iq gnome /etc/sysconfig/desktop
        if [ $? -eq 0 ]; then
            # echo "Found GNOME from /etc/sysconfig/desktop"
            is_gnome=1
        fi
    fi
fi

if [ $is_kde -eq 1 ]; then

    echo "Starting KDE file manager"
    
#   Preferred CentOS 7 graphical file manager
    if [ -e /usr/bin/dolphin ]; then
        /usr/bin/dolphin $1 >& /dev/null &
    else
    
        kfmclient exec $1 >& /dev/null &
    fi
    sleep 1
    exit 1
fi

if [ $is_gnome -eq 1 ]; then
    echo "Starting Gnome file manager"
    nautilus --browser $1 >& /dev/null &
    sleep 1
    exit 1
fi


exit 2
