#!/bin/bash

#   FILE: configd -- 
# AUTHOR: W. Michael Petullo <mike@flyn.org>
#   DATE: 06 December 2005
# 
# Copyright (C) 2005 W. Michael Petullo <mike@flyn.org>
# All rights reserved.
# 
# 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

USAGE=" -f path -s path -x path [OPTION]...

  -h, -?   print this message
  -f path  set the fifo path
  -s path  set the spool directory
  -x path  set the scripts directory"

FIFO=""
SPOOL=""
SCRIPTS=""

error() {
	echo -e usage: ${0##*/} $1 >&2
	exit 1
}

safeexit() {
	/bin/rm -f $FIFO
	/bin/rm -f /var/run/configd/running-scripts
	exit 1
}

mainloop() {
	# Exit only after scripts complete:
	trap "DONE=1" SIGTERM SIGINT EXIT

	DONE=0
	while [ x"$DONE" = x0 ]; do
		# Exit immediately to break out of read:
		trap "safeexit" SIGTERM SIGINT EXIT

		# FIXME: Should we authenticate?
		read SERVICE < $FIFO

		# Return to exiting only after scripts complete:
		trap "DONE=1" SIGTERM SIGINT EXIT

		logger -t configd Received $SERVICE request

		echo "<ul>" > $SPOOL/errorlog
		chmod 660 $SPOOL/errorlog
		chgrp apache $SPOOL/errorlog
		chcon system_u:object_r:httpd_sys_content_t $SPOOL/errorlog

		logger -t configd Executing: $SERVICE
		( cd $SCRIPTS; make --makefile=Makefile.runtime $SERVICE )
		logger -t configd make exited with a status of $?

		echo "</ul>" >> $SPOOL/errorlog

		rm -f /var/run/configd/running-scripts
	done

	safeexit
}

while :;
	do case "$1" in
		-h | "-?" )	
			error "usage: ${0##*/} $USAGE" ;;
		-f )
			FIFO=$2
			shift ;;
		-s )
			SPOOL=$2
			shift ;;
		-x )
			SCRIPTS=$2
			shift ;;
		-?* )
			error "${0##*/}: unrecognised option: $1" ;;
		* )
			break ;;
	esac
	shift
done

[ -z $FIFO ] && error "usage: ${0##*/} $USAGE"
[ -z $SPOOL ] && error "usage: ${0##*/} $USAGE"
[ -z $SCRIPTS ] && error "usage: ${0##*/} $USAGE"
[ -p $FIFO ] && error "${0##*/}: $FIFO already exists"

mkfifo $FIFO || error "${0##*/}: error creating $FIFO"
chcon system_u:object_r:httpd_sys_content_t $FIFO error "${0##*/}: error setting context of $FIFO"

chgrp apache $FIFO || error "${0##*/}: error setting group: $FIFO"
chmod 660 $FIFO || error "${0##*/}: error setting permissions: $FIFO"

mainloop &
echo $! > /var/run/configd.pid
