#!/bin/sh

# The user can specify his prefered WM by setting the WINDOW_MANAGER
# environment variable.
#
# This script has been heavily modified to support Debian's
# alternatives system.

# 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

# Get default wm out of x-window-manager
if [ ! "$WINDOW_MANAGER" ]; then
# Get --default-wm
  if [ "$DEFWM" ]; then
    WINDOW_MANAGER=$DEFWM
  else
  WINDOW_MANAGER=`readlink /etc/alternatives/x-window-manager` 2> /dev/null
  fi
fi

# If no window manager can be found, we default to xterm
if [ ! "$WINDOW_MANAGER" ]; then
  echo "WARNING: No window manager can be found."
  WINDOW_MANAGER=`readlink /etc/alternatives/x-terminal-emulator` 2> /dev/null
fi

# If there is no xterm, they're really screwed.
if [ ! "$WINDOW_MANAGER" ]; then
  echo "ERROR: No window manager and no xterm!"
  exit 1
fi

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

# Store the selected WM so the wm-properties-capplet can find it

if [ ! -d $HOME/.gnome ] ; then
  mkdir -p $HOME/.gnome
  chmod 700 $HOME/.gnome
fi

if [ ! -d $HOME/.gnome/wm-properties ]; then
  mkdir $HOME/.gnome/wm-properties
fi

rm -f $HOME/.gnome/default.wm
cat > $HOME/.gnome/default.wm <<EOF
[Default]
WM=$WINDOW_MANAGER
EOF

rm -f $HOME/.gnome/wm-properties/Config
cat > $HOME/.gnome/wm-properties/Config <<EOF
[Config]
Current=$CURRENT
EOF

exec $WINDOW_MANAGER $OPT1 $OPT2

echo "ERROR: No window manager could run!"
exit 1
