#!/bin/sh /etc/rc.common
# Copyright 2021 Stan Grishin (stangri@melmac.net)
# shellcheck disable=SC2039
PKG_VERSION='dev-test'

# shellcheck disable=SC2034
START=80
# shellcheck disable=SC2034
USE_PROCD=1

if type extra_command 1>/dev/null 2>&1; then
	extra_command 'version' 'Show version information'
else
# shellcheck disable=SC2034
	EXTRA_COMMANDS='version'
fi

readonly PROG=/usr/sbin/nebula

version() { echo "Version: $PKG_VERSION"; }

start_instance() {
	local cfg="$1" port name="${1##*/}"
	port="$(grep -A2 "^listen:" "$cfg" | grep "port: " | awk '{print $2}')"
	procd_open_instance
	procd_set_param command ${PROG} -config "${cfg}"
	procd_set_param stderr 1
	procd_set_param stdout 1
	procd_set_param respawn
	procd_open_data
	json_add_array firewall
		json_add_object ''
		json_add_string type 'rule'
		json_add_string name "Allow-$name"
		json_add_string src 'wan'
		json_add_string dest_port "$port"
		json_add_string proto 'udp'
		json_add_string target 'ACCEPT'
		json_close_object
	json_close_array
	procd_close_data
	procd_close_instance
}

start_service() {
	local f
	for f in /etc/nebula/*.yml; do
		[ -s "$f" ] && start_instance "$f"
	done
}

service_started() { procd_set_config_changed firewall; }
service_stopped() { procd_set_config_changed firewall; }