#!/bin/bash 

LOCKFILE=~/.cdesim.lock

#
# get real WM name from link name
# /usr/X11R6/bin/.fvwm2 -> fvwm2
#
TMPBASE=`basename "$0"`
BASENAME=${TMPBASE#.}

#
# test if script is only used as wrapper for other WMs after cdesim
#
case "$BASENAME" in 

    fvwm|fvwm2|fvwm95|afterstep|bowman|ctwm|mwm)

	if [ -e "$LOCKFILE" ]; then

	    xrdb -load "$LOCKFILE"
	    rm -f "$LOCKFILE"
	fi

	exec ${BASENAME}
	exit 
    ;;

    *)
    ;;
esac

#
# debug switch, almost never used
#
if [ "$1" = "--debug" ]; then

    DEBUG=1
fi

#
# where config information is found
#
XLIBDIR=/usr/X11R6/lib/X11

#
# which locations to check for config files
#
RCFILES="${HOME}/.cdesimrc ${XLIBDIR}/cdesim/.cdesimrc"

#
# a flag
#
FOUND=""

#
# check all above mentioned config files
#
for i in ${RCFILES}
do
    [ "$DEBUG" = 1 ] && echo -n "cdesim: searching for $i... " 1>&2

    if [ -r "$i" ]; then 

	[ "$DEBUG" = 1 ] && echo "found!" 1>&2
	FOUND=$i
	break
    else
	[ "$DEBUG" = 1 ] && echo "not found!" 1>&2
    fi
done

if [ -z "$FOUND" ]; then

    #
    # no config files found
    #
    [ "$DEBUG" = 1 ] && echo "none found!" 1>&2
    echo "cdesim: error: sorry, no configuration file found!" 1>&2
    echo "cdesim: starting fvwm2 instead!" 1>&2
    
    if [ -e "$LOCKFILE" ]; then

	xrdb -load "$LOCKFILE"
	rm -f "$LOCKFILE"
    fi

    exec fvwm2
    exit
fi

#
# load special resources for cdesim
# and save current state
#
xrdb -query > $LOCKFILE
xrdb -merge ${XLIBDIR}/cdesim/Xresources

#
# start fvwm with cdesim config file
#
exec fvwm2 -f ${FOUND}
