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

START=95

# XXX: pid-files are useless because sslh forks after creating them
SERVICE_USE_PID=

start_instance() {
	local section="$1"

	# check if section is enabled (default)
	local enable
	config_get_bool enable "${section}" 'enable' '0'
	[ ${enable} -gt 0 ] || return 1

	local args=""
	local val
	# A) listen parameter
	config_get vals "${section}" listen
	[ -n "${vals}" ] && for val in $vals; do append args "-p${val}"; done
	# B) ssh parameter
	config_get val "${section}" ssh
	[ -n "${val}" ] && append args "--ssh ${val}"
	# C) ssl parameter
	config_get val "${section}" ssl
	[ -n "${val}" ] && append args "--ssl ${val}"
	# D) openvpn parameter
	config_get val "${section}" openvpn
	 [ -n "${val}" ] && append args "--openvpn ${val}"
	# E) tinc parameter
	config_get val "${section}" tinc
	 [ -n "${val}" ] && append args "--tinc ${val}"
	 # F) xmpp parameter
	config_get val "${section}" xmpp
	[ -n "${val}" ] && append args "--xmpp ${val}"
	# G) timeout (before a connection is considered to be SSH)
	config_get val "${section}" timeout
	[ -n "${val}" ] && append args "-t ${val}"
	# H) verbose parameter
	local verbosed
	config_get_bool verbosed "${section}" verbose 0
	[ "${verbosed}" -ne 0 ] && append args "-v"
	 # I) sslh config file (cmd line args override file settings)
	config_get val "${section}" configfile
	[ -n "${val}" ] && append args "-F${val}"

	# Defaults were removed for --user and --pidfile options
	# in sslh 1.11; Define them here instead.
	append args "--user nobody"
	append args "--pidfile /var/run/sslh.pid"

	# XXX: allow more that one instance to run simultaneously
	SERVICE_MATCH_NAME=1 SERVICE_NAME="sslh-dummy-$$" \
	service_start /usr/sbin/sslh ${args}
}

start() {
	config_load 'sslh'
	config_foreach start_instance 'sslh'
}

stop() {
	service_stop /usr/sbin/sslh
}
