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

START=90
STOP=10

USE_PROCD=1
PROG=/usr/bin/tmate-ssh-server

generate_keys() {
	mkdir -p "$1"
	echo "Generating fresh keys"
	ssh-keygen -t "rsa" -f "$1/ssh_host_rsa_key" -N '' > /dev/null
	ssh-keygen -t "ed25519" -f "$1/ssh_host_ed25519_key" -N '' > /dev/null
}

start_service() {
	local ip hostname keys_dir listen_port ssh_port_advertized
	config_load "tmate-http-server"

	procd_open_instance
	procd_set_param command $PROG

	config_get ip main ip
	if [ ! -z "$ip" ]; then
		procd_append_param command -b "$ip"
	fi

	config_get hostname main hostname "$HOSTNAME"
	procd_append_param command -h "$hostname"

	config_get keys_dir main keys_dir "/etc/tmate-ssh-server/keys/"
	if [ ! -f "$keys_dir/ssh_host_rsa_key" ] && \
			[ ! -f "ssh_host_ed25519_key" ]; then
		generate_keys "$keys_dir"
	fi

	procd_append_param command -k "$keys_dir"

	config_get listen_port main listen_port "2222"
	procd_append_param command -p "$listen_port"

	config_get ssh_port_advertized main ssh_port_advertized "$listen_port"
	procd_append_param command -q "$ssh_port_advertized"

	echo "You may use the following settings this in your .tmate.conf:"
	echo ""
	echo "set -g tmate-server-host $hostname"
	echo "set -g tmate-server-port $ssh_port_advertized"
	printf "set -g tmate-server-rsa-fingerprint "
	ssh-keygen -l -E SHA256 -f "$keys_dir/ssh_host_rsa_key.pub" | \
		cut -d ' ' -f 2
	printf "set -g tmate-server-ed25519-fingerprint "
	ssh-keygen -l -E SHA256 -f "$keys_dir/ssh_host_ed25519_key.pub" | \
		cut -d ' ' -f 2

	procd_set_param respawn
	procd_set_param stdout 1
	procd_set_param stderr 1

	procd_close_instance
}

service_triggers() {
	procd_add_reload_trigger "tmate-ssh-server"
}
