#!/bin/sh /etc/rc.common
#
# Copyright (C) 2016-2021 eGloo, Incorporated
#
# This is free software, licensed under the GNU General Public License v2.

START=50
STOP=50

USE_PROCD=1
PROG=/usr/sbin/netifyd

function append_params() {
	procd_append_param command $@
}

function append_ifopts() {
	local filter=0
	local filter_expr=

	for a in $1; do
	    case $a in
	    -F|--device-filter)
	        filter=1
	        procd_append_param command $a
	        ;;
	    -*)
	        if [ $filter -gt 0 ]; then
	            procd_append_param command "${filter_expr#\ }"
	            filter=0; filter_expr=
	        fi
	        procd_append_param command $a
	        ;;
	    *)
	        if [ $filter -gt 0 ]; then
	            a=${a#\"}; a=${a%\"}; a=${a#\'}; a=${a%\'}
	            filter_expr="$filter_expr $a"
	        else
	            procd_append_param command $a
	        fi
	    esac
	done

	if [ $filter -gt 0 ]; then
	    procd_append_param command "${filter_expr#\ }"
	fi
}

function append_internal_if() {
	append_ifopts "-I $@"
}

function append_external_if() {
	append_ifopts "-E $@"
}

start_netifyd() {
	local autoconfig enabled instance

	instance="$1"
	config_get_bool enabled "$instance" enabled 0
	[ "$enabled" -eq 0 ] && return 0

	source /usr/share/netifyd/functions.sh
	load_modules

	procd_open_instance
	procd_set_param file /etc/netifyd.conf
	procd_set_param term_timeout 20
	procd_set_param respawn
	procd_set_param command $PROG -R

	config_list_foreach "$instance" options append_params

	config_get_bool autoconfig "$instance" autoconfig 1

	if [ "$autoconfig" -gt 0 ]; then
	    NETIFYD_AUTODETECT=yes
	    procd_append_param command "$(auto_detect_options)"
	fi

	config_list_foreach "$instance" internal_if append_internal_if
	config_list_foreach "$instance" external_if append_external_if

	procd_close_instance
}

start_service() {
	[ ! -d /var/run/netifyd ] && mkdir -p /var/run/netifyd

	config_load netifyd
	config_foreach start_netifyd netifyd
}
