#!/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
#

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

#read in the arguments
while :; do
  case "$1" in
    --sm-client-id)
      SMID=$2; shift; shift;
      ;;
    --default-wm)
      DEFWM=$2; shift; shift;
      ;;
    *)
      break
      ;;
  esac
done

# WINDOW_MANAGER overrides all

if [ -z "$WINDOW_MANAGER" ] ; then
  # Create a list of window manager we can handle, trying to only use the
  # compositing ones when it makes sense

  xdpyinfo 2> /dev/null | grep -q "^ *Composite$" 2> /dev/null
  IS_X_COMPOSITED=$?

  KNOWN_WM="sawfish sawmill enlightenment icewm wmaker fvwm2 qvwm fvwm twm kwm"
  if [ $IS_X_COMPOSITED -eq 0 ] ; then
    KNOWN_WM="compiz beryl $KNOWN_WM"
  fi
  # metacity is still the default wm in GNOME
  KNOWN_WM="metacity $KNOWN_WM"

  if [ -z "$DEFWM" -o "x$DEFWM" = "xgnome-wm" ]; then
    for wm in $KNOWN_WM ; do
      if type -p "$wm" >/dev/null 2>/dev/null ; then
	WINDOW_MANAGER="$wm"
	break
      fi
    done
  else
    WINDOW_MANAGER="$DEFWM"
  fi
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="xterm"
fi

# Now create options based on the windowmanager used
OPTS=
if [ ! -z "$SMID" ] ; then
  case "${WINDOW_MANAGER##*/}" in
    sawfish|sawmill|metacity)
      OPTS="--sm-client-id=$SMID"
      ;;
    openbox|enlightenment|e16)
      OPTS="--sm-client-id $SMID"
      ;;
    twm)
      OPTS="-clientId $SMID"
      ;;
    lwm)
      OPTS="-s $SMID"
      ;;
    fvwm)
      OPTS="-i $SMID"
      ;;
    compiz)
      OPTS="--sm-client-id $SMID"
      ;;
    beryl)
      OPTS="--sm-client-id $SMID"
      ;;
    #FIXME: add all other windowmanagers here with their proper options
  esac
fi

DECORATOR=
case "${WINDOW_MANAGER##*/}" in
  compiz)
    DECORATOR="gtk-window-decorator"
    OPTS="$OPTS gconf"
    ;;
  beryl)
    DECORATOR="emerald"
    ;;
esac

if [ -n "$DECORATOR" ]; then
  $DECORATOR &
fi
exec $WINDOW_MANAGER $OPTS

echo "ERROR: No window manager could run!"
