#!/bin/sh -e

#  wmanager-loop -- loop running window managers chosen with wmanager
#  Copyright (C) 2000  Tommi Virtanen <tv@debian.org>
#  Copyright (C) 2008, 2009, 2020  Peter Pentchev <roam@ringlet.net>

#  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

# Search .wmanagerrc for the WM specified by the user
check_wm()
{
	local wm esc try

	# A directly specified executable file
	if [ -x "$1" ]; then
		printf -- '%s\n' "$1"
		return 0
	fi

	# No, we'll have to look through .wmanagerrc
	if [ ! -r "$RC" ]; then
		echo "Nonexistent or unreadable config file: $RC" 1>&2
		return 1
	fi

	if expr "$1" : '.*[^A-Za-z0-9_/-]' > /dev/null; then
		echo "Invalid characters in WM specification: $1" 1>&2
		return 1
	fi
	wm="$1"
	esc="$(printf -- '%s\n' "$1" | sed -e 's@/@\\\\/@g')"

	# An exact match
	try="$(awk -F= -v "wm=$wm" '$1 == wm {print $2}' "$RC")"
	if [ -n "$try" ]; then
		echo "$try"
		return 0
	fi

	# An exact match for the program
	try=`awk -F= '$2 ~ /\/'"$esc"'$/ {print $2}' "$RC"`
	if [ -n "$try" ]; then
		set -- $try
		if [ "$#" -gt 1 ]; then
			echo "Ambiguous WM specification '$wm': $@" 1>&2
			return 1
		fi
		printf -- '%s\n' "$try"
		return 0
	fi

	# A WM starting with the specified string
	try="$(awk -F= '$2 ~ /\/'"$esc"'[^\/]*$/ {print $2}' "$RC")"
	if [ -n "$try" ]; then
		set -- $try
		if [ "$#" -gt 1 ]; then
			echo "Ambiguous WM specification '$wm': $@" 1>&2
			return 1
		fi
		printf -- '%s\n' "$try"
		return 0
	fi

	# A WM ending with the specified string
	try="$(awk -F= '$2 ~ /'"$esc"'$/ {print $2}' "$RC")"
	if [ -n "$try" ]; then
		set -- $try
		if [ "$#" -gt 1 ]; then
			echo "Ambiguous WM specification '$wm': $@" 1>&2
			return 1
		fi
		printf -- '%s\n' "$try"
		return 0
	fi

	echo "Invalid WM specification '$wm'" 1>&2
	return 1
}

RC="$HOME/.wmanagerrc"
if [ -n "$WM" ]; then
	WM="$(check_wm "$WM")"
	[ -n "$WM" ] || exit 1
fi
if [ -z "$WM" ] && [ -r "$RC" ]; then
	WM="$(sed 's/^.*=//; q' "$RC")"
fi

if [ -z "$WMTERM" ]; then
	WMTERM='xterm'
	for prog in x-terminal-emulator urxvt rxvt xterm; do
		WMCMD="$(command -v "$prog" || true)"
		if [ -n "$WMCMD" ]; then
			WMTERM="$WMCMD"
			break
		fi
	done
fi

while [ "$WM" != "-1" ]; do
    ${WM:-"$WMTERM"} || true
    WM="$(wmanager "$@" || true)"
done
