#!/bin/sh
#
# setwm - set default window manager
#

VERSION="#VERSION#"

usage(){
echo "Usage: setwm [OPTION]... [WM]..."
echo "Set the default window manager for the current user, or"
echo "the default window manager for new users."
echo
echo "  -s, --systemwide        set default wm for new users"
echo "  -l, --list              list available window managers"
echo "  -h, --help              print this help and exit"
echo "  -v, --version           output version information and exit"
echo
echo "Report bugs to <johne@rootlinux.org>."
exit 0
}

displayversion(){
echo "setwm (rltools) $VERSION"
exit 0
}

if [ "$1" = "-h" -o "$1" = "--help" ]; then
  usage
fi

if [ "$1" = "-v" -o "$1" = "--version" ]; then
  displayversion
fi

if [ "$1" = "-l" -o "$1" = "--list" -o "$1" = "" ]; then
  if [ -d /etc/X11/xinit ]; then
    echo "available window managers:";echo
    if [ -f ~/.xinitrc ]; then
      CURR_WM=`vdir ~/.xinitrc | cut -f3 -d.`
    fi
    for i in /etc/X11/xinit/xinitrc.*; do
      WM=`echo $i | cut -f2 -d.`
      if [ "$CURR_WM" = "$WM" ]; then
        WM="$WM (current)"
      fi
      if ! [ "$WM" = "sample" -o "$WM" = "all" -o "$WM" = "d" ]; then
        echo $WM
      fi
    done
    exit 0
   else
    echo "no window managers available."
    exit 1
  fi
fi    

if [ "$1" = "-s" -o "$1" = "--systemwide" ]; then
  if [ ! "$UID" = 0 ]; then
    echo "setwm: you must be root."
    exit 1
  fi
  if [ "$2" = "" ]; then
    echo "setwm: no window manager specificed."
    exit 1
   else
    if ! [ -x /etc/X11/xinit/xinitrc.$2 ]; then
      echo "setwm: $2: no such window manager."
      exit 1
     else
      if ( ln -sf /etc/X11/xinit/xinitrc.$2 /etc/X11/xinit/xinitrc >/dev/null 2>/dev/null ); then
        echo "setwm: default systemwide wm set to $2."
	exit 0
       else
        echo "setwm: error setting default window manager."
	exit 1
      fi
    fi
  fi
fi 

if ! [ -x /etc/X11/xinit/xinitrc.$1 ]; then
  echo "setwm: $1: no such window manager."
  exit 1
 else
  if ( ln -sf /etc/X11/xinit/xinitrc.$1 ~/.xinitrc ); then
    echo "setwm: default wm for `whoami` set to $1."
   else
    echo "setwm: error setting default window manager."
  fi
fi