#!/bin/sh

# The user can specify his prefered WM by setting the WINDOW_MANAGER
# environment variable.
#
# If this is not set, we search a list of known windowmanagers and use
# the first one that is found in the users's PATH
#

check_cmd () {
  local FULLPATH
 
  if [ -x "$1" ]; then
    echo "$1"
  else
    FULLPATH=`which "$1" 2> /dev/null`
    if [ $? = 0 -a -x "$FULLPATH" ]; then
      echo "$FULLPATH"
    fi
  fi
}

GCONF_KEY="/desktop/gnome/applications/window_manager/default"

# sm-client-id value
SMID=
# default-wm value
DEFWM=

#read in the arguments
GET=
for n in "$@" ; do
  case "$GET" in
    smid)
      SMID=$n
      GET=
      ;;
    defwm)
      DEFWM=$n
      GET=
      ;;
    *)
      case "$n" in
        --sm-client-id)
          GET=smid
          ;;
        --default-wm)
          GET=defwm
          ;;
      esac
      ;;
  esac
done

# WINDOW_MANAGER overrides all

if [ -z "$WINDOW_MANAGER" ] ; then
  if [ -z "$DEFWM" -o "x$DEFWM" = "xgnome-wm" ]; then
    WINDOW_MANAGER=`gconftool-2 -g "$GCONF_KEY" 2> /dev/null`
  else
    WINDOW_MANAGER=$DEFWM
  fi
fi

if [ -n "$WINDOW_MANAGER" ] ; then
  WINDOW_MANAGER=`check_cmd "$WINDOW_MANAGER"`
fi

if [ -z "$WINDOW_MANAGER" ] ; then
  for wm in metacity sawfish sawmill enlightenment icewm wmaker fvwm2 qvwm fvwm twm kwm ; do
    WINDOW_MANAGER=`check_cmd "$wm"`
    if [ -n "$WINDOW_MANAGER" ] ; then
      break
    fi
  done
fi

# If no window manager can be found, we default to xterm

if [ -z "$WINDOW_MANAGER" ] ; then
  echo "WARNING: No window manager can be found."
  WINDOW_MANAGER=`check_cmd xterm`
fi

# Now create options OPT1 and OPT2 based on the windowmanager used
OPT1=
OPT2=
if [ ! -z "$SMID" ] ; then
  case `basename $WINDOW_MANAGER` in
    sawfish|sawmill|metacity)
      OPT1=--sm-client-id=$SMID
      ;;
    enlightenment|twm)
      OPT1=-clientId
      OPT2=$SMID
      ;;
    #FIXME: add all other windowmanagers here with their proper options
  esac
fi

# Store the selected WM so the wm-properties-capplet can find it
gconftool-2 -t string -s "$GCONF_KEY" "$WINDOW_MANAGER"

exec $WINDOW_MANAGER $OPT1 $OPT2

echo "ERROR: No window manager could run!"
