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

# Migrate compiz to compiz-manager
if [ "x$WINDOW_MANAGER" = "xcompiz" ]; then
  WINDOW_MANAGER="compiz-manager"
fi
if [ "x$DEFWM" = "xcompiz" ]; then
  DEFWM="compiz-manager"
fi

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

  if [ "x$XDG_CONFIG_HOME" = "x" ]; then
    COMPIZ_ENABLED_FILE="$HOME/.config/compiz/enable-compiz"
  else
    COMPIZ_ENABLED_FILE="$XDG_CONFIG_HOME/compiz/enable-compiz"
  fi

  KNOWN_WM="metacity sawfish sawmill enlightenment icewm wmaker fvwm2 qvwm fvwm twm kwm"

  if [ -f "$COMPIZ_ENABLED_FILE" ] ; then
    KNOWN_WM="compiz-manager $KNOWN_WM"
  fi

  OLDIFS=$IFS
  if [ -z "$DEFWM" -o "x$DEFWM" = "xgnome-wm" ]; then
      
    for wm in $KNOWN_WM ; do
      IFS=":"
      for dir in $PATH ; do
	if [ -x "$dir/$wm" ] ; then
	  WINDOW_MANAGER="$dir/$wm"
    	  break 2
	fi
      done
      IFS=$OLDIFS
    done

  else
    WINDOW_MANAGER=$DEFWM
  fi
  IFS=$OLDIFS
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 OPT1, OPT2 and OPT3 based on the windowmanager used
OPT1=
OPT2=
OPT3=
OPT4=
if [ ! -z "$SMID" ] ; then
  case `basename $WINDOW_MANAGER` in
    sawfish|sawmill|metacity)
      OPT1=--sm-client-id=$SMID
      ;;
    openbox|enlightenment|e16)
      OPT1=--sm-client-id
      OPT2=$SMID
      ;;
    twm)
      OPT1=-clientId
      OPT2=$SMID
      ;;
    lwm)
      OPT1=-s
      OPT2=$SMID
      ;;
    fvwm)
      OPT1=-i
      OPT2=$SMID
      ;;
    compiz-manager)
      OPT1=--sm-client-id
      OPT2=$SMID
      ;;
    #FIXME: add all other windowmanagers here with their proper options
  esac
fi

exec $WINDOW_MANAGER $OPT1 $OPT2

echo "ERROR: No window manager could run!"
