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

START=90
STOP=10
USE_PROCD=1

append_bool() {
	config_get_bool tbool "$1" "$2"
	v=$(echo "$2" | sed 's/_/-/g')
	[ -z "$tbool" ] && tbool="$3"
	[ "$tbool" -eq 1 ] && procd_append_param command "--${v}"
}

append_bool_no() {
	config_get_bool tbool "$1" "$2"
	v=$(echo "$2" | sed 's/_/-/g')
	[ -z "$tbool" ] && tbool="$3"
	[ "$tbool" -eq 0 ] && procd_append_param command "--no-${v}"
	[ "$tbool" -eq 1 ] && procd_append_param command "--${v}"
}

append_param() {
	config_get tparam "$1" "$2"
	name=$(echo "$2" | sed 's/_/-/g')
	[ -n "$tparam" ] && procd_append_param command "--${name}=${tparam}"
}

start_instance() {
	cfg=$1

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

	procd_open_instance "$cfg"
	procd_set_param command /usr/bin/readsb
	procd_append_param command "--quiet"

	procd_set_param respawn
	procd_set_param stderr "1"
	procd_set_param stdout "1"

	append_bool "$cfg" beast_crc_off 0
	append_bool "$cfg" beast_df045_on 0
	append_bool "$cfg" beast_df1117_on 0
	append_bool "$cfg" beast_fec_off 0
	append_bool "$cfg" beast_mlat_off 0
	append_bool "$cfg" beast_modeac 0
	append_bool "$cfg" dcfilter 0
	append_bool "$cfg" enable_agc 0
	append_bool "$cfg" enable_biastee 0
	append_bool "$cfg" forward_mlat 0
	append_bool "$cfg" gnss 0
	append_bool "$cfg" metric 0
	append_bool "$cfg" mlat 0
	append_bool "$cfg" modeac 0
	append_bool "$cfg" net 1
	append_bool "$cfg" net_only 0
	append_bool "$cfg" net_verbatim 0
	append_bool "$cfg" no_crc_check 0
	append_bool "$cfg" no_modeac_auto 0
	append_bool "$cfg" onlyaddr 0
	append_bool "$cfg" stats 0
	append_bool "$cfg" stats_range 0

	append_bool_no "$cfg" fix 1

	for param in \
		beast_serial \
		debug \
		device \
		device_type \
		freq \
		gain \
		json_location_accuracy \
		lat \
		lon \
		max_range \
		net_beast_reduce_interval \
		net_beast_reduce_out_port \
		net_bi_port \
		net_bind_address \
		net_bo_port \
		net_buffer \
		ppm \
		stats_every \
		write_json \
		write_json_every
	do
		append_param "$cfg" "$param"
	done

	config_get net_connector "$cfg" "net_connector"
	[ -z "$net_connector" ] || {
		for conn in $net_connector; do
			procd_append_param command --net-connector="$conn"
		done
	}

	procd_close_instance
}

start_service() {
	config_load readsb
	config_foreach start_instance readsb
}
