#!/bin/sh /etc/rc.common
#UDP Echo Server software
# Copyright (C) 2020 iopsys Software Solutions AB
#Author: Amin Ben Ramdhane <amin.benramdhane@pivasoftware.com>

START=99
STOP=02

USE_PROCD=1
PROG="/usr/sbin/udpechoserverd"

start_service() {
	local enable_udpechoserver port_udpechoserver address_udpechoserver

	enable_udpechoserver="$(uci -q get udpechoserver.udpechoserver.enable)"
	port_udpechoserver="$(uci -q get udpechoserver.udpechoserver.server_port)"
	address_udpechoserver="$(uci -q get udpechoserver.udpechoserver.address)"


	if [ "${enable_udpechoserver}" -eq "1" ] && [ "$port_udpechoserver" -ne "0" ]; then
		if [ -z "$address_udpechoserver" ]; then
			iptables -w -I zone_wan_input -p udp --dport "$port_udpechoserver" -j ACCEPT -m comment --comment "Open UDPechoserver port"
			ip6tables -w -I zone_wan_input -p udp --dport "$port_udpechoserver" -j ACCEPT -m comment --comment "Open UDPechoserver port"
		elif [[ "$address_udpechoserver" =~ .*:.* ]]; then
			ip6tables -w -I zone_wan_input -p udp --dport "$port_udpechoserver" -j ACCEPT -m comment --comment "Open UDPechoserver port"
		else
			iptables -w -I zone_wan_input -p udp --dport "$port_udpechoserver" -j ACCEPT -m comment --comment "Open UDPechoserver port"
		fi

		procd_open_instance
		procd_set_param command "$PROG"
		procd_set_param respawn "3" "7" "0"
		procd_close_instance
	fi
}

stop_service() {
	# Remove the USPechoserver ports created earlier
	while iptables -w -nL zone_wan_input --line-numbers | grep "Open UDPechoserver port" > /dev/null; do
		iptables -w -D zone_wan_input "$(iptables -w -nL zone_wan_input --line-numbers | grep "Open UDPechoserver port" | head -1|awk '{print $1}')";
	done

	while ip6tables -w -nL zone_wan_input --line-numbers | grep "Open UDPechoserver port" > /dev/null; do
		ip6tables -w -D zone_wan_input "$(ip6tables -w -nL zone_wan_input --line-numbers | grep "Open UDPechoserver port" | head -1|awk '{print $1}')";
	done

	plus_enable="$(uci -q -c /var/state get udpechoserver.udpechoserver.plus)"
	if [ -n "${plus_enable}" ]; then
		uci -q set udpechoserver.udpechoserver.plus="${plus_enable}"
		uci commit udpechoserver
	fi
}

reload_service() {
	stop
	start 
}

service_triggers() {
	procd_add_reload_trigger udpechoserver
}
