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

START=90

USE_PROCD=1

LIST_SEP="
"
ZT_COMMAND=/usr/bin/zerotier-one

section_enabled() {
	config_get_bool enabled "$1" 'enabled' 0
	[ $enabled -gt 0 ]
}

start_instance() {
	local cfg="$1"
	local port secret interface
	local ARGS=""

	section_enabled "$cfg" || return 1

	mkdir -p /var/lib/zerotier-one/networks.d/

	config_get_bool port $cfg 'port'
	config_get secret $cfg 'secret'
	config_get interface $cfg 'interface'

	if [ -n "$port" ]; then
		ARGS="$ARGS -p$port"
	fi

	if [ "$secret" = "generate" ]; then
		echo "Generate secret - please wait..."
		local tmp="/tmp/zt.$cfg.secret"
		zerotier-idtool generate "$tmp" > /dev/null
		secret="$(cat $tmp)"
		rm "$tmp"

		uci set zerotier.$cfg.secret="$secret"
		uci commit zerotier
	fi

	if [ -n "$secret" ]; then
		echo "$secret" > /var/lib/zerotier-one/identity.secret
		#make sure there is not previous dentity.public
		rm -f /var/lib/zerotier-one/identity.public
	fi

	add_join() {
		#an (empty) config file will cause ZT to join a network
		touch /var/lib/zerotier-one/networks.d/$1.conf
	}

	config_list_foreach $cfg 'join' add_join

	procd_open_instance
	procd_add_reload_interface_trigger "$interface"
	procd_set_param command $ZT_COMMAND $ARGS
	procd_close_instance
}

service_triggers() {
       procd_add_reload_trigger zerotier
}

start_service() {
	config_load 'zerotier'
	config_foreach start_instance 'zerotier'
}
