#! /bin/sh

. /etc/init.d/functions.sh
. /etc/conf.d/sts-web

case "$1" in
	start)
		# Run only if camera is locked.
		LOCKED=$(bootblocktool -err -c RSLOCKED 2>/dev/null) &&
			[ $LOCKED = yes ] || exit 0
		UNLOCKED=$(bootblocktool -err -c RSUNLOCKED 2>/dev/null) &&
			[ $UNLOCKED = yes ] && exit 0 || :

		begin "Initializing locked camera"

		if grep -q 'RootPwdSet no' /etc/sysconfig/rootpassword.conf; then
			# First time camera boots.

			# Disable ECN by default to make sure no buggy
			# routers drop our packets.
			sed -i -re 's/^(net\.ipv4\.tcp_ecn)=1/\1=0/' /etc/sysctl.conf &&
				echo 0 > /proc/sys/net/ipv4/tcp_ecn ||
				warning "Failed to disable ECN."

			# Enable axisstc by default.
			sed -r -i 's/^(Enabled[[:blank:]]*=[[:blank:]]*"?)[^"]*("?)$/\1yes\2/' 				/etc/axisstc.conf || warning "Failed to enable axisstc."

			# Disable ONVIF by default.
			sed -r -i 's/^(Enabled[[:blank:]]*=[[:blank:]]*"?)[^"]*("?)$/\1no\2/' 				/etc/sysconfig/ws_enabled.conf || warning "Failed to disable ONVIF."
		fi

		# Set new password
		QUERY_STRING="action=update&user=root&pwd=$PASS" 		    /usr/html/axis-cgi/admin/pwdgrp.cgi || end $?

		# Since parhand not yet started, make sure
		# root.System.RootPwdSet="yes".
		sed -i 's/RootPwdSet no/RootPwdSet yes/' 			/etc/sysconfig/rootpassword.conf || end $?

		# Create sessions for accessing:
		CREATESESSION=/usr/html/axis-cgi/admin/createsession.cgi
		# Live video
		QUERY_STRING=$QUERY_STRING_VIDEO $CREATESESSION || end $?
		QUERY_STRING=$QUERY_STRING_IMAGE $CREATESESSION || end $?

		# Focus setting
		QUERY_STRING=$QUERY_STRING_FOCUS $CREATESESSION || end $?

		# - Network parameters
		QUERY_STRING=$QUERY_STRING_NETWORK $CREATESESSION || end $?

		# - Save Network parameters
		QUERY_STRING=$QUERY_STRING_SAVE_NETWORK $CREATESESSION || end $?

		# - Wlan parameters
		QUERY_STRING=$QUERY_STRING_WLAN $CREATESESSION || end $?

		# - Save Wlan parameters
		QUERY_STRING=$QUERY_STRING_SAVE_WLAN $CREATESESSION || end $?

		# - Server report
		QUERY_STRING=$QUERY_STRING_REPORT $CREATESESSION || end $?

		# - Third part license
		QUERY_STRING=$QUERY_STRING_LICENSE $CREATESESSION || end $?

		# Use limited web interface as web server first page.
		mount --bind /usr/html/limitedIndex.shtml /usr/html/index.shtml
		end $?
		;;
	restart)
		# Only run on boot
		end $?
		;;
	stop)
		end $?
		;;
	*)
		error "Usage: $0 start|stop|restart"
		;;
esac

exit 0
