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

START=90
USE_PROCD=1
NAME=mbusd


mbusd_instance() {
	[ "$2" = 0 ] || {
		echo "Validation failed"
		return 1
	}
	[ "$enabled" -gt 0 ] || return 1


	[ "$parity" = 0 ] && parity=n || parity=y
	[ "$rts" = 0 ] && rts=


	procd_open_instance mbusd-$port
	procd_set_param command /usr/bin/mbusd \
		-d \
		-L - \
		-P $port \
		-v $loglevel \
		${max_connections:+-C $max_connections} \
		${timeout:+-T $timeout} \
		-p $device \
		-s $speed \
		-m ${databits}${parity}${stopbits} \
		${rts:+-t} \
		${rtu_retries:+-N $rtu_retries} \
		${rtu_wait:+-W $rtu_wait}

	procd_set_param stdout 1
	procd_set_param stderr 1
	procd_set_param respawn

	procd_close_instance
}

validate_section_mbusd() {
	uci_load_validate mbusd mbusd "$1" "$2" \
		'enabled:bool:1' \
		'port:port:502' \
		'loglevel:uinteger:2' \
		'max_connections:uinteger' \
		'timeout:uinteger' \
		'device:string' \
		'speed:uinteger' \
		'databits:uinteger' \
		'parity:bool' \
		'stopbits:uinteger' \
		'rts:bool:0' \
		'rtu_retries:uinteger' \
		'rtu_wait:uinteger'
}

start_service() {
	config_load "$NAME"
	config_foreach validate_section_mbusd mbusd mbusd_instance
}

service_triggers() {
	procd_add_reload_trigger "$NAME"
	procd_add_validation validate_section_mbusd
}
