#!/bin/sh


# shellcheck source=opennet/packages/on-core/files/usr/lib/opennet/on-helper.sh
. "${IPKG_INSTROOT:-}/usr/lib/opennet/on-helper.sh"


configure_tunnel_network() {
	local uci_prefix=network.on_vpn

	# Abbruch falls das Netzwerk schon vorhanden ist
	[ -n "$(uci_get "$uci_prefix")" ] && return

	# add new network to configuration (to be recognized by olsrd)
	uci set "${uci_prefix}=interface"
	uci set "${uci_prefix}.proto=none"
	uci set "${uci_prefix}.device=tun-on-user"

	apply_changes network
}


configure_tunnel_firewall() {
	local was_changed=0
	local uci_prefix
	uci_prefix=$(find_first_uci_section firewall zone "name=$ZONE_TUNNEL")

	# Zone erzeugen, falls sie noch nicht vorhanden ist
	if [ -z "$(uci_get "$uci_prefix")" ]; then
		# Zone fuer ausgehenden Verkehr definieren
		uci_prefix=firewall.$(uci add firewall zone)
		uci set "${uci_prefix}.name=$ZONE_TUNNEL"
		uci add_list "${uci_prefix}.network=$NETWORK_TUNNEL"
		uci set "${uci_prefix}.forward=REJECT"
		uci set "${uci_prefix}.input=REJECT"
		uci set "${uci_prefix}.output=ACCEPT"
		uci set "${uci_prefix}.masq=1"
		was_changed=1
	fi
	create_uci_section_if_missing firewall forwarding \
			"src=$ZONE_LOCAL" "dest=$ZONE_TUNNEL" \
		&& was_changed=1
	create_uci_section_if_missing firewall rule \
			"src=$ZONE_TUNNEL" "dest_port=22" "target=ACCEPT" "name=on-user-ssh" \
		&& was_changed=1
	create_uci_section_if_missing firewall rule \
			"src=$ZONE_TUNNEL" "proto=icmp" "target=ACCEPT" "name=on-user-icmp" \
		&& was_changed=1
	[ "$was_changed" = "0" ] && return 0
	apply_changes firewall
}


configure_tunnel_network
configure_tunnel_firewall
