#! /bin/sh

. /etc/init.d/functions.sh
conffile=/etc/conf.d/parhand
. $conffile

case "$1" in
	start)
		begin "Starting parameter handler"
		start_daemon /bin/parhand $PARHAND_OPTIONS
		status=$?

		# Check if this is first-time boot ever or after factory default
		if [ "$PARHAND_SET_DEFAULTS" = yes ]; then
			information "detected first-time boot"

			# Find all root.-parameters in bootblock and set them
			# in parhand.
			parameters=`bootblocktool -l | grep '^root\.'`
			param_was_set=

			old_ifs=$IFS
			IFS="
"
			for param in $parameters; do
				name="${param%%=*}"
				value="${param#*=}"
				information "setting $name: \"$value\""
				if parhandclient --nosync set "$name" "$value"
				then
					param_was_set=yes
				else
					warning "Failed to set \"$name\"!"
				fi
			done
			IFS=$old_ifs

			if [ -n "$param_was_set" ]; then
				information "syncing parameters"
				parhandclient sync > /dev/null ||
					warning "Failed to sync parameters!"
			fi

			# Mark as done in conf-file so it doesn't happen again
			# until factory default.
			information "writing new config"
			conf=`sed s/[[:space:]]*PARHAND_SET_DEFAULTS=yes[[:space:]]*$/PARHAND_SET_DEFAULTS=no/ < "$conffile"`
			echo "$conf" > "$conffile" || \
				warning "Failed to edit configuration file!"
		fi
		end $status
		;;
	stop)
		begin "Stopping parameter handler"
		stop_daemon /bin/parhand
		end $?
		;;
	*)
		error "Usage: $0 start|stop"
		;;
esac

exit 0
