#!/bin/sh -e
#
# $Id: runwm,v 1.3 2004/06/12 10:32:53 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

Usage()
{
	[ "$1" = 0 ] || exec >&2
	cat <<EOF
Usage: $PROG <window manager> [args]
       $PROG --print <window manager> [args]
       $PROG --list
       $PROG --help
EOF
	[ -n "$1" ] && exit "$1" || exit
}

[ "$1" != '--help' ] || Usage 0

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

if [ $# -lt 1 ]; then
	Usage
fi

wm=`printf %s "$1" |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
		printf '%s\n' "$*"
		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=`printf %s "$name0" |tr '[:upper:]' '[:lower:]'`
		if [ "$wm" = '--list' ]; then
			printf '%s\n' "$name0"
			[ "$name" != default ] || found_default=1
			continue
		fi
		if [ "$wm" = default -o "$wm" = "$name" ]; then
			Exec "$exec" "$@"
		fi
	fi
done

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

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