#!/bin/sh /etc/rc.common
USE_PROCD=1
START=45
PORT=33123

DAEMON=/usr/sbin/babeld
pidfile=/var/run/gluon-babeld.pid
CONFIGFILE=/etc/gluon-babeld.conf
BABELOPTSFILE=/tmp/addn-babelopts
touch $BABELOPTSFILE

start_service() {
	procd_open_instance
	procd_set_param command $DAEMON
	procd_append_param command -D -I "$pidfile" -G "$PORT" -c "$CONFIGFILE" $(cat $BABELOPTSFILE) babeldummydoesnotexist
	procd_set_param respawn ${respawn_threshold:-60} ${respawn_timeout:-5} ${respawn_retry:-0}
	procd_set_param stderr 1
	procd_set_param stdout 1
	procd_close_instance
}

echotobabel() {
	local count=0
	local line="$1"
	local maxretries=10
	while ! (echo -e "$line" | busybox nc ::1 "$PORT" >/dev/null 2>&1)
	do
		sleep 1
		echo retrying to connect to babeld in PID $$, waited ${count}s >&2
		count=$((count+1))
		if [ $count -gt $maxretries ]; then
			return 1
		fi
	done
	return 0
}

waitforsocket() {
	echotobabel "dump"
	[ $? -gt 0 ] && { echo "Failed to connect to babeld socket on port $PORT, assuming the service was not started properly"; exit 43; }
}

reload_service() {
	waitforsocket

	for i in $(ubus call network.interface dump | jsonfilter -e "@.interface[@.proto='gluon_mesh' && @.up=true].device")
	do
	if ! echotobabel dump|grep "add interface"|grep -q $i
	then
		echotobabel "interface $i update-interval 300"
	fi
	done

	for i in $(echotobabel "dump"|grep "add interface"|cut -d" " -f3)
	do
		if ! ubus call network.interface dump | jsonfilter -e "@.interface[@.proto='gluon_mesh' && @.up=true].device"|grep -q $i
		then
			echotobabel "flush interface $i"
		fi
	done
}

service_triggers() {
	local script=$(readlink "$initscript")
	local name=$(basename "${script:-$initscript}")

	procd_open_trigger
	procd_add_raw_trigger "interface.*" 0 "/etc/init.d/$name" reload
	procd_close_trigger
}

service_started() {
# make sure the init script does not finish until babeld is actually up.
# unfortunately procd will still start multiple instances of the same script which is why waitforsocket is also run on reload
	waitforsocket
}
stop_service(){
	kill $(pgrep -P 1 babeld)
}
status() {
	kill -USR1 $(pgrep -P 1 babeld)
}
