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

START=75
STOP=10
CONFIGFILE="/tmp/ser2net.conf"

USE_PROCD=1
PROG=/usr/sbin/ser2net

start_service() {
	config_load 'ser2net'

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

	ser2net_create_config config || return 1
	procd_open_instance
	procd_set_param command "$PROG" -n -c "$CONFIGFILE"
	procd_close_instance
}

ser2net_create_config() {
	local cfg=$1
	local port
	local device
	
	config_get port $cfg port
	config_get device $cfg device
	[ -z "$port" -o -t "$device" ] && return 1

	local protocol
	local timeout
	local options

	config_get protocol $cfg protocol
	config_get timeout $cfg timeout
	config_get options $cfg options

	if [ -z "$options" ]; then
		echo "$port":"$protocol":"$timeout":"$device" >> "$CONFIGFILE
	else
		echo "$port":"$protocol":"$timeout":"$device":"$options" >> "$CONFIGFILE"
	fi
}
