#!/bin/sh

proxy="$1"
local_port="$2"
port_min="$3"
port_max="$4"
nslookup_command="${VOIP_NSLOOKUP:-nslookup}"
iptables_command="${VOIP_IPTABLES:-iptables}"
ip6tables_command="${VOIP_IP6TABLES:-ip6tables}"

[ -n "$proxy" ] && [ -n "$local_port" ] && [ -n "$port_min" ] && [ -n "$port_max" ] || exit 2

case "$proxy" in
	*:*|*[!0-9.]* )
		case "$proxy" in
			*:* ) proxy_addresses="$proxy" ;;
			* )
				proxy_addresses=$("$nslookup_command" "$proxy" 2>/dev/null |
					awk '/^Name:/ { answer = 1; next }
					     answer && /^Address [0-9]+: / { print $3 }')
				;;
		esac
		;;
	* ) proxy_addresses="$proxy" ;;
esac

if [ -z "$proxy_addresses" ]; then
	echo "voip-sip-filter: unable to resolve SIP proxy $proxy" >&2
	exit 1
fi

need_rtp4=
need_rtp6=
for proxy_address in $proxy_addresses; do
	case "$proxy_address" in
		*:* ) filter_command="$ip6tables_command"; need_rtp6=1 ;;
		*[!0-9.]* )
			echo "voip-sip-filter: invalid resolved address $proxy_address" >&2
			exit 1
			;;
		* ) filter_command="$iptables_command"; need_rtp4=1 ;;
	esac
	"$filter_command" -A SIP_FILTER -p udp -s "$proxy_address" --dport "$local_port" -j ACCEPT || exit 1
	"$filter_command" -A SIP_FILTER -p tcp -s "$proxy_address" --dport "$local_port" -j ACCEPT || exit 1
done

[ -z "$need_rtp4" ] || "$iptables_command" -A SIP_FILTER -p udp --dport "$port_min:$port_max" -j ACCEPT || exit 1
[ -z "$need_rtp6" ] || "$ip6tables_command" -A SIP_FILTER -p udp --dport "$port_min:$port_max" -j ACCEPT || exit 1
