#!/bin/sh

# This script runs fvwm with fvwm-themes config.  It should be run under X.
# Put a call to this script as the last line of your .Xclients or .xinitrc.

prefix=/usr/X11R6
: ${ROOT_PREFIX=}

: ${FVWM_USERDIR=$HOME/.fvwm}
rcName=themes-rc
rcFile=$FVWM_USERDIR/$rcName
rcName2=themes-rc-2
rcFile2=$FVWM_USERDIR/$rcName2
themesName=themes
themesDir=$FVWM_USERDIR/$themesName
currentThemeName=current
currentThemeDir=$themesDir/$currentThemeName
startDir=`pwd`
isNewSession=0

# Arguments
fvwmArgs=""
whoseArgs="my"
start=yes
fvwm="fvwm2"
session="main"

while [ "x$1" != "x" ]; do
	case "$1" in
	--)
		whoseArgs="fvwm" ;;
	*)
		if [ "$whoseArgs" = "fvwm" ]; then
			fvwmArgs="$fvwmArgs $1"
		else
			case "$1" in
			--no-start|-no-start|-n)
				start=no ;;
			--fvwm|-fvwm|-f)
				shift
				fvwm="$1" ;;
			--session|-session|-s)
				shift
 				if [ "$1" = "--" ]; then
					whoseArgs="fvwm"
				else
					session="$1"
				fi ;;
			esac
		fi ;;
	esac
	shift
done

realCurrentThemeName="current-$session"
realCurrentThemeDir="$themesDir/$realCurrentThemeName"
destRcFile2="$themesName/$realCurrentThemeName/$rcName2"

[ -d $FVWM_USERDIR ] || mkdir $FVWM_USERDIR
# create the symbolic links
# POSIX says that we can have symlink to a not existing file.
# However some 2.3.x Linux kernels and may be 2.4.x do not support this???
[ -d $themesDir ] || mkdir $themesDir
cd $themesDir
if [ ! -d $realCurrentThemeName ]; then
	mkdir $realCurrentThemeName
	isNewSession=1
fi
rm -rf $currentThemeName
ln -s $realCurrentThemeName $currentThemeName
cd $FVWM_USERDIR
if [ ! -f $destRcFile2 ]; then
	touch $destRcFile2
	isNewSession=1
fi
rm -f $rcName2
ln -s $destRcFile2 $rcName2

# check whether this is a first run
test -f $rcFile -a "`head -1 $rcFile 2>/dev/null | cut -d' ' -f3`" = "0.4.1"
isNewVersion="$?"
if [ "$isNewVersion" = 1 -o "$isNewSession" = 1 ]; then
	if [ "$isNewVersion" = 1 ]; then
		echo '[FVWM-Themes]: Welcome to FVWM Themes 0.4.1!'
		xmessage -g 400x100+0+0 -xrm "*form*background:rgb:c0/c0/a0" -xrm "*form*okay*background:rgb:90/90/7a" -xrm "*textSink*font:lucidasans-18" -xrm "*form*message*background:rgb:f0/f0/c0" 'Welcome to FVWM Themes 0.4.1!' 2>/dev/null &
	else
		echo "[FVWM-Themes]: Initial $session FVWM Themes session"
	fi
	${prefix}/bin/fvwm-themes-config --reset
	${prefix}/bin/fvwm-themes-config --load @personal 2>/dev/null
fi

# check that /usr/X11R6/bin (fvwm2) is in $PATH
if ! which fvwm2 >/dev/null; then
	PATH="/usr/X11R6/bin:$PATH"
fi

# check that ${prefix}/bin (fvwm-themes-config) is in $PATH
if ! which fvwm-themes-config >/dev/null; then
	PATH="${prefix}/bin:$PATH"
fi

cd $startDir
echo "[FVWM-Themes]: Starting FVWM under the $session fvwm-themes session"
if [ "$start" = "yes" ]; then
    exec $fvwm -f "$rcName" $fvwmArgs
fi;
