#!/bin/sh /etc/rc.common
. /lib/functions.sh
# Copyright (C) 2006 OpenWrt.org

START=99

log() {
	logger -t "WireGuard Init.d : " "$@"
}

chk_zone() {
	local config=$1
	
	config_get src $config src
	config_get dest $config dest
	if [ $src = "lan" -a $dest = "wg" ]; then
		uci set firewall."$config".dest="wan"
		uci commit firewall
	fi
}

check_config () {
	log "Check Client Interfaces"
	uci delete network.wg0
	uci delete network.wg1
	uci commit network
	uci set network.wg0=interface
	uci set network.wg0.proto="wireguard"
	uci set network.wg0.auto="0"
	uci set network.wg0.private_key=""
	uci set network.wg0.listen_port=""
	uci add_list network.wg0.addresses=""
	uci set network.wg1=interface
	uci set network.wg1.proto="wireguard"
	uci set network.wg1.auto="0"
	uci set network.wg1.private_key=""
	uci set network.wg1.listen_port=""
	uci add_list network.wg1.addresses=""
	uci commit network
	
	uci delete firewall.wgzone
	uci delete firewall.wgwforward
	uci delete firewall.wwgforward
	uci delete firewall.lwgforward
	uci delete firewall.wglforward
	uci commit firewall
	uci set firewall.wgzone=zone
	uci set firewall.wgzone.name="wg"
	uci set firewall.wgzone.forward="ACCEPT"
	uci set firewall.wgzone.output="ACCEPT"
	uci set firewall.wgzone.network="wg0 wg1"
	uci set firewall.wgzone.input="ACCEPT"
	uci set firewall.wgzone.masq="1"
	uci set firewall.wgzone.mtu_fix="1"
	uci commit firewall
	
	config_load firewall
	config_foreach chk_zone forwarding

	/etc/init.d/firewall restart
}

chk_start() {
	local config=$1
	
	config_get auto $config auto
	uci set wireguard."$config".active="0"
	uci commit wireguard
	if [ $auto = '1' ]; then
		/usr/lib/wireguard/startvpn.sh $config
	else
		/usr/lib/wireguard/stopvpn.sh $config
	fi
}

start() {
	uci set wireguard.settings.client="0"
	uci set wireguard.settings.server="0"
	uci commit wireguard
	if [ ! -e /etc/openvpn ]; then
		mkdir /etc/openvpn
	fi
	check_config
	
	config_load wireguard
	config_foreach chk_start wireguard
	if [ -e /etc/crontabs/root ]; then
		sed -i '/wireguard_watchdog/d' /etc/crontabs/root
	fi
	echo '* * * * * /usr/bin/wireguard_watchdog' >> /etc/crontabs/root
	/etc/init.d/cron restart
}