#!/bin/sh -e

# exec 2>/dev/console
# set -x

. /etc/init.d/functions.sh
CONF=/etc/conf.d/http_auth
. $CONF
HAP="HTTP Authentication Policy"


get_RootPwdSet () {
	echo -n $(sed -rne 's|^"?yes_no"?[[:space:]]+RootPwdSet[[:space:]]+([^[:space:]]+)|\1|p' /etc/sysconfig/rootpassword.conf) || return 1
}

case "$1" in
	start|restart)
		begin "Setting appropriate $HAP"

		PWD_SET=$(get_RootPwdSet) ||
			error "Cannot get parameter RootPwdSet"

		information "RootPwdSet='$PWD_SET'"
		if [ "$AUTHENTICATION_POLICY_SET" != yes ]; then
			# If QOP value is missing set it to default value.
			[ "$QOP" ] || QOP=no

			if [ "$PWD_SET" = yes ]; then
				# Upgraded and not factory default:
				AUTHENTICATION_POLICY=basic
				information "$HAP set to Basic Only."
			else
				# New or factory default
				information "Initializing the digest" 					    "authentication file"
				http_auth_init || error "http_auth_init failed"
				AUTHENTICATION_POLICY=basic_digest
				information "$HAP set to Basic + Digest."
			fi
			cat > $CONF <<-EOF
				AUTHENTICATION_POLICY=$AUTHENTICATION_POLICY
				AUTHENTICATION_POLICY_SET=yes
				QOP=$QOP
EOF
		else
			case "$AUTHENTICATION_POLICY" in
				basic_digest)
					information "$HAP kept at Basic +" 						    "Digest."
					;;
				digest)
					information "$HAP kept at Digest Only."
					;;
				basic)
					information "$HAP kept at Basic Only."
					;;
				*)
					error "Unexpected value for $HAP:" 					      "$AUTHENTICATION_POLICY"
					;;
			esac

		fi
		end $?
		;;
	stop)
		;;
	*)
		error "Usage: $0 start|stop|restart"
		;;
esac

exit 0
