#!/bin/bash
#
# Startup script for the Apache Web Server
#
# chkconfig: - 85 15
# description: Apache is a World Wide Web server.  It is used to serve \
#	       HTML files and CGI.
# processname: httpd
# pidfile: /var/run/httpd.pid
# config: /etc/httpd/conf/access.conf
# config: /etc/httpd/conf/httpd.conf
# config: /etc/httpd/conf/srm.conf

# Source function library.
DOMAIN=base-services
. /etc/rc.d/init.d/functions

# Source additional OPTIONS if we have them.
if [ -f /etc/sysconfig/apache ] ; then
	. /etc/sysconfig/apache
fi

# Path to the httpd binary.
httpd=/usr/sbin/httpd
prog=httpd
RETVAL=0

# Change the major functions into functions.
moduleargs() {
	moduledir=/usr/lib/apache
	moduleargs=`
	/usr/bin/find ${moduledir} -type f -perm -0100 -name "*.so" | awk '{\
		gsub(".*/","");\
		gsub("^mod_","");\
		gsub("^lib","");\
		gsub("\.so$","");\
		print "-DHAVE_" toupper($0)}'`
	echo ${moduleargs}
}
start() {
	LINE1=`getmsg httpd_start_1`
	LINE2=`getmsg httpd_start_2`
	$LCD_STOP
	$LCD_SWRITE "$LINE1" "$LINE2" >/dev/null 2>&1 & 
	echo -n "$LINE1 $LINE2: "

	daemon $httpd `moduleargs` $OPTIONS

	RETVAL=$?
	echo
	[ $RETVAL = 0 ] && touch /var/lock/subsys/httpd
	return $RETVAL
}

kill_httpd()
{
	echo -n " $prog"
	count=0
	while [ $count != 30 ]; do
		pid=`pidofproc $prog`
		if [ "$pid" != "" ]; then
			kill -TERM $pid
			count=$(($count+1))
			usleep 10000
		else
			echo -n " ok"
			return 0
		fi
	done

	# make sure it is really dead
	rm -f /var/run/httpd.pid
	pid=`pidofproc $prog`
	if [ "$pid" != "" ]; then
		kill -KILL $pid
	fi
	
	pid=`pidofproc $prog`
	if [ "$pid" == "" ]; then
		echo -n " ok"
		return 0
	else
		echo -n " ERROR!"
		return 1
	fi
}

stop() {
	LINE1=`getmsg httpd_stop_1`
	LINE2=`getmsg httpd_stop_2`
	$LCD_STOP
	$LCD_SWRITE "$LINE1" "$LINE2" >/dev/null 2>&1 &
	echo -n "$LINE1 $LINE2: "
	
	# library functions are nice, but unfortunately apache
	# takes a long time to die.  use custom process killer instead.
	kill_httpd
	RETVAL=$?
	echo
	[ $RETVAL = 0 ] && rm -f /var/lock/subsys/httpd /var/run/httpd.pid
}

# See how we were called.
case "$1" in
  start)
	start
	;;
  stop)
	stop
	;;
  status)
	`pidof $httpd | awk \
	'{
		if (split($0, junk) > 2) { \
			exit(0); \
		} else { \
			exit(1); \
		} \
	}'`
	RETVAL=$?
	;;
  restart)
	stop
	start
	;;
  reload)
	echo -n $"Reloading $prog: "
	killproc $httpd -USR1
	RETVAL=$?
	echo
	;;
  condrestart)
	if [ -f /var/run/httpd.pid ] ; then
		stop
		start
	fi
	;;
  *)
	echo $"Usage: $prog {start|stop|restart|reload|condrestart|status}"
	exit 1
esac

exit $RETVAL
