#!/bin/sh
# Launch explorer
#
# License : GNU GPL
# (c) Eko M. Budi, 2004
# (c) Vector Linux, 2004

# Determine user through ownership of console. Barring the absence of
# perl or misconfigured X, this command cannot fail.
USER=$(ls -l /dev/console | perl -e \
       'local $_ = <>; split / +/; print $_[2], "\n";');

# Konqueror seems to be acceptable now. I have no problems
# with it returning. Even so, we should tailor the list of file managers
# according to the current window manager. This relies on .wm_style or
# .dmrc being present in $USER's home directory
#
# This also relies on /var/run being readable.

## Determine what display manager is running
DM=$(ps aux | grep $(cat /var/run/xdm.pid) | \
       perl -e 'local $_ = <>;
       split / +/;
       for (@_) { ($_ =~ "dm") ? print $_, "\n" : 0; }')
DM=`basename $DM`

## Now find where the window manager prefs are stored
case $DM in
     kdm) if [ -e "/home/$USER/.dmrc" ]; then
              WM_CONFIG="/home/$USER/.dmrc"
          else unset WM_CONFIG
          fi ;;
     wdm) if [ -e "/home/$USER/.wm_style" ]; then
              WM_CONFIG="/home/$USER/.wm_style"
          else unset WM_CONFIG
          fi ;;
     ## I mean...who still uses xdm?? :D
     *) unset WM_CONFIG ;;
esac

# Lightweight, general purpose file managers that could serve under any
# window manager or desktop environment.
GENERAL_EXPLORERS="rox emelfm endeavour2 xfe"

# Now set priority of file manager choice according to window manager.
# For KDE, we will prefer konqueror; for XFce, we will prefer xffm
if [ "$WM_CONFIG" ]; then
     case `cat $WM_CONFIG` in
         *kde*) PROG_LIST="konqueror $GENERAL_EXPLORERS" ;;
         *xfce4*) PROG_LIST="xffm $GENERAL_EXPLORERS" ;;
         *) PROG_LIST="$GENERAL_EXPLORERS"
     esac
else
     PROG_LIST="$GENERAL_EXPLORERS"
fi

case "$1" in
  -h|--help)
     echo "Usage:"
     echo "$0 [options]"
     echo "Launch one of: $PROG_LIST"
     exit 0
     ;;
esac

for TRY in $EXPLORER $PROG_LIST ; do
    if which $TRY 2> /dev/null; then
   case $TRY in
       konqueror)
      if [ "$1" ]; then
          exec konqueror file:$1
      else
          exec konqueror file:$HOME
      fi
      ;;
       rox)
      exec rox -n "$@"
      ;;
       *)   
      exec $TRY "$@"
      ;;
   esac
    fi
done

message "ERROR" "Could not find either one of: " "$PROG_LIST"
exit 1
