#!/bin/sh /etc/rc.common
# Copyright (C) 2015 OpenWrt.org

START=50
STOP=20
USE_PROCD=1

append_arg() {
	local cfg="$1"
	local opt="$2"
	local var="$3"
	local def="$4"
	local val
	config_get val "$cfg" "$var"
	[ -n "$val" ] || [ -n "$def" ] && procd_append_param command "$opt" "${val:-$def}"
}

start_instance() {
	local cfg="$1"
	local enabled

	config_get_bool enabled "$cfg" 'enabled' 1
	[ "$enabled" -gt 0 ] || return 0

	procd_open_instance
	procd_set_param command /usr/bin/u2pnpd
	append_arg "$cfg" -s httpsURL
	append_arg "$cfg" --interface interface
	append_arg "$cfg" --manufacturer manufacturer
	append_arg "$cfg" --manufacturerURL manufacturerURL
	append_arg "$cfg" --modelDescription modelDescription
	append_arg "$cfg" --modelName modelName
	append_arg "$cfg" --modelNumber modelNumber
	append_arg "$cfg" --modelURL modelURL
	append_arg "$cfg" --serialNumber serialNumber
	append_arg "$cfg" --friendlyName friendlyName
	append_arg "$cfg" --uuid uuid
	procd_set_param file /etc/config/u2pnpd
	procd_set_param respawn
	procd_close_instance
}

start_service() {
	config_load u2pnpd && config_foreach start_instance u2pnpd
}

service_triggers() {
	procd_add_reload_trigger u2pnpd
}
