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

START=99
STOP=50
USE_PROCD=1

NAME=ttyd
PROG=/usr/bin/$NAME

validate_section_ttyd()
{
	uci_load_validate ttyd ttyd "$1" "$2" \
		'enable:bool:1' \
		'port:port' \
		'interface:string' \
		'credential:string' \
		'uid:uinteger' \
		'gid:uinteger' \
		'signal:uinteger' \
		'url_arg:bool' \
		'readonly:bool' \
		'client_option:list(string)' \
		'terminal_type:string' \
		'check_origin:bool' \
		'max_clients:uinteger' \
		'once:bool' \
		'index:string' \
		'ipv6:bool' \
		'ssl:bool' \
		'ssl_cert:file' \
		'ssl_key:file' \
		'ssl_ca:file' \
		'debug:uinteger' \
		'command:string'
}

ttyd_instance()
{
	[ "$2" = 0 ] || {
		echo "validation failed"
		return 1
	}

	[ "$enable" = 0 ] && return 1
	[ -z "$command" ] && return 1

	[ "${interface::1}" = @ ] && {
		interface=$(
			. /lib/functions/network.sh
			network_get_device device "${interface:1}"
			echo -n "$device"
		)
	}

	[ "$url_arg" = 0 ] && url_arg=""
	[ "$readonly" = 0 ] && readonly=""
	[ "$check_origin" = 0 ] && check_origin=""
	[ "$once" = 0 ] && once=""
	[ "$ipv6" = 0 ] && ipv6=""
	[ "$ssl" = 0 ] && ssl=""

	procd_open_instance
	procd_set_param command "$PROG" \
		${port:+-p $port} \
		${interface:+-i $interface} \
		${credential:+-c $credential} \
		${uid:+-u $uid} \
		${gid:+-g $gid} \
		${signal:+-s $signal} \
		${url_arg:+-a} \
		${readonly:+-R} \
		${terminal_type:+-T $terminal_type} \
		${check_origin:+-O} \
		${max_clients:+-m $max_clients} \
		${once:+-o} \
		${index:+-I $index} \
		${ipv6:+-6} \
		${ssl:+-S} \
		${ssl_cert:+-C $ssl_cert} \
		${ssl_key:+-K $ssl_key} \
		${ssl_ca:+-A $ssl_ca} \
		${debug:+-d $debug}
	config_list_foreach "$1" client_option "procd_append_param command -t"
	procd_append_param command $command
	procd_set_param stdout 1
	procd_set_param stderr 1
	procd_close_instance
}

start_service() {
	config_load "$NAME"
	config_foreach validate_section_ttyd ttyd ttyd_instance
}

shutdown() {
	# close all open connections
	killall "$NAME"
}

service_triggers() {
	procd_add_reload_trigger "$NAME"
}