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

START=98
STOP=1

USE_PROCD=1

PROG=/usr/bin/bcg
CONF=/tmp/etc/bigclown-gateway.conf

append() {
	local cfg="$1"
	local uci_name="$2"
	local out_name="$3"
	local default="$4"
	config_get val $cfg $uci_name $default
	if [ -n "$val" ]; then
	  echo "$out_name $val" >> $CONF
	fi
}

start_service() {
	config_load bigclown-gateway

	local enabled
	config_get_bool enabled gateway enabled "0"
	[ "$enabled" = "1" ] || {
		echo "Bigclown gateway service disabled"
		exit 1
	}

	rm -rf $CONF
	echo "Generating bigclown-gateway config file in $CONF"

	append gateway name 'name:' usb-dongle
	# TODO add hotplug script and use different default here
	append gateway device 'device:' /dev/ttyUSB0
	append gateway automatic_rename_kit_nodes 'automatic_rename_kit_nodes:' 1
	append gateway base_topic_prefix 'base_topic_prefix:'

	echo "mqtt:" >> $CONF
	append mqtt host '  host:' localhost
	append mqtt port '  port:' 1883
	append mqtt cafile '  cafile:'
	append mqtt certfile '  certfile:'
	append mqtt keyfile '  keyfile:'

	procd_open_instance
	procd_set_param respawn ${respawn_threshold:-3600} ${respawn_timeout:-5} ${respawn_retry:-5}
	procd_set_param command "$PROG" -c "$CONF"
	procd_set_param stdout 1
	procd_set_param stderr 1
	procd_close_instance
}

service_triggers() {
	procd_add_reload_trigger 'bigclown-gateway'
}
