#!/bin/sh /etc/rc.common
# shellcheck disable=SC2154,SC2034

START=90
STOP=10

USE_PROCD=1

validate_section() {
	uci_validate_section otb-remote remote "$1" \
		'enable:bool:1'            \
		'host:host'                \
		'port:port'                \
		'forwarded_port:port'      \
		'server_public_key:string' \
		'remote_public_key:string'
}

start_instance() {
	validate_section "$1" || return

	[ "$enable" = "0" ] && return

	[ -z "${host}" ] && return
	[ -z "${port}" ] && return
	[ -z "${forwarded_port}" ] && return

	[ -z "${server_public_key}" ] && return
	[ -z "${remote_public_key}" ] && return

	home=/tmp/otb-remote/$1
	dir=${home}/.ssh

	mkdir -p -m 0700 "${dir}"
	echo "${host} ${server_public_key% *}" > "${dir}/known_hosts"

	# Add the remote user pubkey in the authorized_keys of root
	if ! grep -sq "$1" /etc/dropbear/authorized_keys; then
		echo "${remote_public_key} ${1}" >> /etc/dropbear/authorized_keys
	fi

	chmod 0600 "${dir}/known_hosts" /etc/dropbear/authorized_keys

	procd_open_instance
	procd_set_param command /usr/bin/ssh -l limited-user "$host" -p "$port" -N -R "6666:0.0.0.0:$forwarded_port" -K 30 -i /etc/dropbear/dropbear_ed25519_host_key
	procd_set_param respawn 0 10 0
	procd_set_param stderr 1
	procd_set_param user root
	procd_set_param env HOME="${home}"
	procd_close_instance
}

start_service() {
	config_load otb-remote
	config_foreach start_instance remote
}

service_triggers() {
	procd_add_reload_trigger otb-remote
}
