#!/bin/sh

# Startup script for FVWM-Crystal project (http://fvwm-crystal.berlios.de/)
# Written by: Maciej Delmanowski <harnir@post.pl>

# This script searchs for configuration files in different locations, picks
# one and launches fvwm2 with specified configuration file.

# You can set 'FVWMCRYSTAL_BASECONFIG' environment variable to omit
# searching for configuration and use the given path.

# Name of the configuration file
configname=config

# Default path
# if a variable 'configfile' is defined in the environment, its value is
# preserved; otherwise, the scripts look for configuration in common places.
configfile="$HOME/fvwm-crystal/$configname"
if [ -n "$FVWMCRYSTAL_BASECONFIG" ]
	then
		configfile="$FVWMCRYSTAL_BASECONFIG"
	elif [ -f "$HOME/fvwm-crystal/$configname" ]
	then
		configfile=$HOME/fvwm-crystal/$configname;
	elif [ -f "`dirname ${0}`/../share/fvwm-crystal/fvwm/$configname" ]
	then
		configfile="`dirname ${0}`/../share/fvwm-crystal/fvwm/$configname";
fi

# This scripts will also kill the helper scripts when needed
cleanup() {
	exitcode="0"
	# remove orfaned fullscreen files
	rm /tmp/fullscreen* 2>/dev/null
	# check for old instances and PID orfaned files
	for i in $(ls /tmp/crystal_desktopcheckmount_* 2>/dev/null); do
		pid=$(echo $i | sed -e 's:/tmp/crystal_desktopcheckmount_::')
		kill $pid 2>/dev/null
		rm $i
		exitcode="1"
	done
	for i in $(ls /tmp/crystal_update_infoline_* 2>/dev/null); do
		pid=$(echo $i | sed -e 's:/tmp/crystal_update_infoline_::')
		kill $pid 2>/dev/null
		rm $i
		exitcode="1"
	done
	for i in $(ls /tmp/crystal_mplayer_* 2>/dev/null); do
		pid=$(echo $i | sed -e 's:/tmp/crystal_mplayer_::')
		kill $pid 2>/dev/null
		kill -9 $pid 2>/dev/null
		rm $i
		exitcode="1"
	done
	# exit if not startup
	if [ "$1" = "previous" ]; then
		echo "FVWM-Crystal starting..."
	else
		echo "exit = $exitcode"
		exit $exitcode
	fi
}

# trap if interupted
trap cleanup INT QUIT TERM

# cleanup previuos instances
cleanup previous

exec fvwm -f $configfile $@
