#!/bin/sh -e
#
# $Id: runwm,v 1.2 2003/01/24 16:56:11 ldv Exp $
# Copyright (C) 2002  Dmitry V. Levin <ldv@altlinux.org>
#
# Executes window manager using wm.d database.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#

PROG="${0##*/}"
WM_DIR=/etc/X11/wmsession.d

print_only=
if [ "$1" = '--print' ]; then
	print_only=1
	shift
fi

if [ $# -lt 1 ]; then
	echo "usage: $PROG <window manager> [args]" >&2
	echo "       $PROG --print <window manager> [args]" >&2
	echo "       $PROG --list" >&2
	exit 1
fi

wm=`echo "$1" |/usr/bin/tr '[:upper:]' '[:lower:]'`
shift

TryExecWM()
{
	local f
	for f in "$@"; do
		if [ -x "$f" ]; then
			exec "$f" ||:
		fi
	done
}

Exec()
{
	if [ -n "$print_only" ]; then
		echo "$@"
		exit
	else
		exec "$@"
	fi
}	

if [ "$wm" = failsafe ]; then
	if [ -n "$print_only" ]; then
		echo "/usr/X11R6/bin/xterm -geometry 100x25+0+0 $@"
	else
		/usr/X11R6/bin/xterm -geometry 100x25+0+0 &
		TryExecWM /usr/X11R6/bin/icewm-light /usr/X11R6/bin/twm
	fi
	exit
fi

if [ "$wm" = default -a -f "$WM_DIR/default" ]; then
	exec=`sed -ne 's,^EXEC=\(/.\+\)$,\1,pg' "$WM_DIR/default" |tail -1`
	if [ -n "$exec" ] && [ -x "$exec" ]; then
		Exec "$WM_DIR/default/exec" "$@"
	fi
fi

found_default=

for d in "$WM_DIR"/*; do
	[ -r "$d" ] || continue
	n=${d##*/}
	[ -n "${n##*.*}" ] || continue
	exec=`sed -ne 's,^EXEC=\(/.\+\)$,\1,pg' "$d" |tail -1`
	if [ -x "$exec" ]; then
		name0=`sed -ne 's,^NAME=\(.\+\)$,\1,pg' "$d" |tail -1`
		[ -n "$name0" ] || continue
		name=`echo "$name0" |/usr/bin/tr '[:upper:]' '[:lower:]'`
		if [ "$wm" = '--list' ]; then
			echo "$name0"
			[ "$name" != default ] || found_default=1
			continue
		fi
		if [ "$wm" = default -o "$wm" = "$name" ]; then
			Exec "$exec" "$@"
		fi
	fi
done

if [ "$wm" != '--list' ]; then
	echo "$PROG: window manager \"$wm\" not found." >&2
	exit 1
fi

[ -n "$found_default" ] || echo default
