#!/bin/sh

. /etc/init.d/functions.sh
. /etc/conf.d/ws_init

DESCRIPTION="Web Services bootstrap"
CONF=/etc/sysconfig/ws_enabled.conf
PWD_CONF=/etc/sysconfig/rootpassword.conf


conditional_disable () {
	local pwd_set ws_enabled ws_enabled_set no_users

	# If file exists...
	if [ -f /etc/ws/security/ws_enabled_set ]; then
		# then WebService.Enabled have been manually modified, so don't change it
		return 0
	fi 

	# Has the root password been configured?
	pwd_set=$(sed -rne 's|^"?yes_no"?[[:blank:]]+RootPwdSet[[:blank:]]+([^[:blank:]]+)|\1|p' $PWD_CONF) ||
		return 1

	if [ "$pwd_set" = yes ]; then
		# Is Web Services enabled or not?
		ws_enabled=$(sed -rne 's|^Enabled[[:blank:]]*=[[:blank:]]*"?([[:alpha:]]+)"?|\1|p' $CONF) ||
			return 1

		if [ "$ws_enabled" = yes ]; then
			# Are there any Web Services users defined yet?
			[ -s /etc/ws/security/ws_users ]
			no_users=$?

			# Disable Web Services if we have no Web Services users
			# and the system root password has been configured.
			if [ $no_users -ne 0 ]; then
				information "Disabling Web Services"

				# At startup before parhand is running, change
				# in parameter file directly, otherwise use
				# parhandclient to change parameter.
				if [ "$1" = rootpwdset ]; then
					parhandclient --nocgi set WebService.Enabled no
				else
					sed -ri 's/^(Enabled[[:blank:]]*=[[:blank:]]*"?)[[:alpha:]]+("?)/\1no\2/' $CONF ||
						return 1
				fi
			fi
		fi
	fi
}

case "$1" in
	start)
		begin "Initializing $DESCRIPTION"
		conditional_disable $2
		end $?
		;;
	stop)
		;;
	restart)
		begin "Re-initializing $DESCRIPTION"
		conditional_disable $2
		end $?
		;;
	*)
		# rootpwdset argument should be used after start up
		# so that parhand parameter and saved parameter match.
		error "Usage: $0 start|stop|restart [rootpwdset]"
		;;
esac

exit 0
