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

. /lib/functions/network.sh

USE_PROCD=1
START=99

BIN=/usr/bin/rtty

start_rtty() {
    local cfg="$1"
    local interface ifname id description host port ssl heartbeat

    uci_validate_section rtty rtty "${1}" \
        'interface:uci("network", "@interface"):lan' \
        'id:maxlength(63)' \
        'description:maxlength(126)' \
        'host:host' \
        'port:port' \
        'ssl:bool:0' \
        'heartbeat:uinteger:5' \
        'keepalive:uinteger:5'
    
    [ $? -ne 0 ] && {
        echo "validation failed" >&2
        return 1
    }

    [ -n "$interface" ] && network_get_device ifname "$interface"

    [ -z "$id" ] && {
	uci set rtty.@rtty[0].id=`hostname`
	id=$(hostname)
	uci set rtty.@rtty[0].description=`hostname`
	description=$(hostname)
	uci commit rtty
    }
    id=`uci get rtty.@rtty[0].id`
    hn=$(hostname)
    if [ "$id" != "$hn" ]; then
	uci set rtty.@rtty[0].id=`hostname`
	id=$(hostname)
	uci set rtty.@rtty[0].description=`hostname`
	description=$(hostname)
	uci commit rtty
    fi

    [ -z "$ifname" -a -z "$id" ] && {
        echo "You must specify an interface or ID" >&2
        return 1
    }

    [ -z "$host" ] && {
        echo "host required" >&2
        return 1
    }
    
    [ -z "$port" ] && {
        echo "port required" >&2
        return 1
    }

    [ -z "$heartbeat" ] && {
        uci set rtty.@rtty[0].heartbeat=5
        heartbeat=5
        uci commit rtty
    }

    procd_open_instance
    procd_set_param command $BIN -h $host -p $port -a 
    [ -n "$id" ] && procd_append_param command -I "$id"
    [ -n "$description" ] && procd_append_param command -d "$description"
    [ "$ssl" = "1" ] && procd_append_param command -s
    [ -n "$heartbeat" ] && procd_append_param command -H $heartbeat
    procd_set_param respawn
    procd_close_instance
}

start_service() {
    config_load rtty
    config_foreach start_rtty rtty
}

