#!/bin/sh
#
# Load the glorytun config
#
# Author: Ycarus (Yannick Chabanois) <ycarus@zugaina.org>
# Released under GPL 3 or later

[ "$ACTION" = ifup -o "$ACTION" = ifupdate ] || exit 0

. /lib/functions.sh
. /lib/functions/network.sh

set_default() {
	local localip
	local remoteip
	local config="$1"
	local iface
	config_get enable "$config" enable
	config_get iface "$config" dev
	[ "$iface" = "$DEVICE" ] && [ "$enable" = "1" ] && {
		config_get localip "$config" localip
		config_get remoteip "$config" remoteip
		config_get kxtimeout "$config" kxtimeout "7d"
		config_get timetolerance "$config" timetolerance "10m"
		config_get keepalive "$config" keepalive "25s"
		[ "$remoteip" != "" ] && [ "$localip" != "" ] &&  ifconfig $DEVICE $localip pointopoint $remoteip up
		# Hotplug scripts run one at a time: wait for glorytun in the
		# background, and not forever, or every later event waits too
		(
			count=0
			while ! glorytun-udp list 2>/dev/null | grep -qxF "$iface"; do
				count=$((count + 1))
				[ "$count" -gt 10 ] && exit 0
				sleep 1
			done
			glorytun-udp set dev "$iface" kxtimeout "$kxtimeout" timetolerance "$timetolerance" keepalive "$keepalive"
		) </dev/null >/dev/null 2>&1 &
	}
}

config_load glorytun-udp
config_foreach set_default glorytun-udp
