#!/bin/sh /etc/rc.common

START=90
STOP=10

USE_PROCD=1

SERVICE=v4l2camera
PROG=/usr/bin/$SERVICE

error() {
        logger -t "$SERVICE" "$@"
}

start_instance() {
	local s="$1"

	config_get_bool enabled "$1" 'enabled' 0
	[ $enabled -eq 0 ] && return

	# validate device
	config_get device "$s" 'device'
	if [ ! -c "$device" ]; then
		error "device '$device' does not exist"
		return 1
	fi

	# get options
	config_get rtspport "$s" 'rtspport'
	config_get httpport "$s" 'httpport'
        config_get mode "$s" 'mode'
        config_get format "$s" 'format'

	# build args
	local args="-p /usr/share/$SERVICE"
	args="$args -R $rtspport"
	args="$args -P $httpport"
	if [ ! -z "$mode" ]; then
		args="$args -G$mode"
        fi
        if [ ! -z "$format" ]; then
                args="$args -f$format"
        fi
	cmd="$PROG $args $device"

	# procd stuff
	procd_open_instance
	procd_set_param file /etc/config/$SERVICE
	procd_set_param command $cmd
	procd_set_param stdout 1
	procd_set_param stderr 1
	procd_add_mdns "http" "tcp" "$httpport" "daemon=$SERVICE" "path=/"
	procd_close_instance
}

start_service() {
	config_load "$SERVICE"
	config_foreach start_instance "$SERVICE"
}

service_triggers() {
	procd_add_reload_trigger "$SERVICE"
}
