#!/bin/sh

openvpn_port="$(uci -q get openvpn.myvpn.port)"
[ -z "$openvpn_port" ] && openvpn_port=1194

uci -q batch <<-EOF >/dev/null
	delete network.vpn0
	set network.vpn0=interface
	set network.vpn0.ifname='tun0'
	set network.vpn0.proto='none'

	commit network

	delete firewall.openvpn
	set firewall.openvpn=rule
	set firewall.openvpn.name='openvpn'
	set firewall.openvpn.target='ACCEPT'
	set firewall.openvpn.src='wan'
	set firewall.openvpn.proto='tcp udp'
	set firewall.openvpn.dest_port="$openvpn_port"

	delete firewall.vpn
	set firewall.vpn=zone
	set firewall.vpn.name='vpn'
	set firewall.vpn.input='ACCEPT'
	set firewall.vpn.forward='ACCEPT'
	set firewall.vpn.output='ACCEPT'
	set firewall.vpn.masq='1'
	set firewall.vpn.network='vpn0'

	delete firewall.vpntowan
	set firewall.vpntowan=forwarding
	set firewall.vpntowan.src='vpn'
	set firewall.vpntowan.dest='wan'

	delete firewall.vpntolan
	set firewall.vpntolan=forwarding
	set firewall.vpntolan.src='vpn'
	set firewall.vpntolan.dest='lan'

	delete firewall.lantovpn
	set firewall.lantovpn=forwarding
	set firewall.lantovpn.src='lan'
	set firewall.lantovpn.dest='vpn'

	commit firewall
EOF

if [ ! -f "/etc/openvpn/pki/ca.crt" ]; then
	sh /etc/openvpn/renewcert.sh 2>&1 >/dev/null
fi

rm -f /tmp/luci-indexcache
exit 0
