#!/bin/sh 

CFG_FILE=/proc/flash/script
TMP_DIR=/tmp
CONFIG_FILE_LIST=/etc/config_files
CONFIG_FILE=$TMP_DIR/updating_config

do_restart ()
{
	[ ! -s $CONFIG_FILE.restart ] && return
	echo -n "Evaluating new config files ... "
	mkdir -p $TMP_DIR/do_restart
	echo "#!/bin/sh " > $CONFIG_FILE.sh
	zcat $CONFIG_FILE.bk.gz | tar -px -C $TMP_DIR/do_restart
	cat $CONFIG_FILE.restart | while read file RST_PROC
	do
		cmp $file $TMP_DIR/do_restart/$file > /dev/null 2>&1
		if [ $? -ne 0 ]; then
			cat $CONFIG_FILE.sh |grep "$RST_PROC" >/dev/null 2>&1
			if [ $? -ne 0 ]; then
				echo "$RST_PROC" >> $CONFIG_FILE.sh
			fi
		fi
	done
	rm -rf $TMP_DIR/do_restart
	echo "done."
	if [ -s $CONFIG_FILE.sh ]; then
		echo -n "Restarting processes ... "
		/bin/sh $CONFIG_FILE.sh > /dev/null 2>&1
		if [ $? -ne 0 ]; then
			echo "error."
			do_exit "*** ERROR: failed to restart processes" 1
		else
			echo "done."
		fi
		rm -f $CONFIG_FILE.sh
	fi
	rm -f $CONFIG_FILE.restart
	return 0
}

do_exit ()
{
	CONFIG_FILE=$TMP_DIR/updating_config
	if [ "$2" = "" ]; then
		EXIT_CODE=1
	else
		EXIT_CODE=$2
	fi
	rm -rf $TMP_DIR/do_restart	
	rm -f $CONFIG_FILE*
	if [ "$1" = "" ]; then
		echo -e "*** Aborting..."
	else 
		echo -e "$1"
	fi
	exit $EXIT_CODE
}


# Trap signals so that this application is not interrupted
trap do_exit SIGTERM SIGINT SIGQUIT SIGHUP
umask 77

cat $CONFIG_FILE_LIST | grep -v ^# | while read file_l MARK RST_PROC
do
	for file in $file_l
	do
  		[ -z "$file" -o -z "$MARK" -o -z "$RST_PROC" ] && continue
  		if [ -L $file -o -f $file -o -d $file ] ; then
			if [ "x$MARK" = "x*" ]; then
    				echo "$file $RST_PROC" >> $CONFIG_FILE.restart
			fi
  		else
    			if [ "$MSG" = "" ] ; then
      				MSG="Partially"
    			fi
    			echo "$0 : File '$file' does not exist !"
		fi
	done
done 

cp -f $CFG_FILE $CONFIG_FILE.bk.gz
do_restart

CONFIG_FILE=$TMP_DIR/updating_config
rm -f $CONFIG_FILE*
echo "done."
exit 0
