#!/bin/sh

# Usage: vpn-select <path-to-hood-file>

. /usr/share/libubox/jshn.sh

hoodfile="$1"

make_config() {
# remove old config
>/etc/config/tunneldigger
rm /tmp/fastd_fff_peers/*
count=0
Index=1
json_load "$(cat "$hoodfile")"
json_select vpn
# get fastd peers
while json_select "$Index" > /dev/null
do
	json_get_var protocol protocol
	if [ "$protocol" = "fastd" ]; then
		json_get_var servername name
		filename="/etc/fastd/fff/peers/$servername"
		echo "#name \"${servername}\";" > "$filename"
		json_get_var key key
		echo "key \"${key}\";" >> "$filename"
		json_get_var address address
		json_get_var port port
		echo "remote \"${address}\" port ${port};" >> "$filename"
		echo "" >> "$filename"
		echo "float yes;" >> "$filename"
		
		# ask for Broker and select the tunnel
		if [ "l2tp" = "$(wget -T10 "${address}/vpn.txt" -O - 2>/dev/null)" ]; then
			# Gateway offers l2tp
			L2PORT=$((port + 10000))
			UUID=$hostname

			uci set tunneldigger.$count=broker
			uci set tunneldigger.$count.address="${address}:$L2PORT"
			uci set tunneldigger.$count.uuid="$UUID"
			uci set tunneldigger.$count.interface="l2tp$count"
			uci set tunneldigger.$count.enabled="1"
			uci set tunneldigger.$count.hook_script='/etc/tunneldigger/tunneldigger.hook'
			uci -c /tmp commit tunneldigger
			count=$((count + 1))
			# remove this fastd-peer
			rm "$filename"
		fi
	fi
	json_select ".." # back to vpn
	Index=$(( Index + 1 ))
done
json_select ".." # back to root
}

# main

# Only do something if file is there and not empty; otherwise exit 1
if [ -s "$hoodfile" ]; then
	# set some vars
	hostname=$(cat /proc/sys/kernel/hostname)
	mac=$(awk '{ mac=toupper($1); gsub(":", "", mac); print mac }' /sys/class/net/br-mesh/address 2>/dev/null)
	[ "$hostname" = "LEDE" ] && hostname=""
	[ "$hostname" = "" ] &&  hostname="$mac"

	if [ ! -d /tmp/fastd_fff_peers ]; then
		# first run after reboot
		mkdir /tmp/fastd_fff_peers
		make_config
		# start fastd only if there are some peers left
		[ "$(ls /etc/fastd/fff/peers/* 2>/dev/null)" ] && /etc/init.d/fastd start
		/etc/init.d/tunneldigger start
	else
		# check if new tunneldigger conf is different
		sumold=$(sha256sum /etc/config/tunneldigger)
		make_config
		sumnew=$(sha256sum /etc/config/tunneldigger)
		[ "$sumnew" != "$sumold" ] && /etc/init.d/tunneldigger restart
		/etc/init.d/fastd reload

		# fastd start/stop for various situations
		pidfile="/tmp/run/fastd.fff.pid"
		if [ "$(ls /etc/fastd/fff/peers/* 2>/dev/null)" ]; then
			([ -s "$pidfile" ] && [ -d "/proc/$(cat "$pidfile")" ]) || /etc/init.d/fastd start
		else
			([ -s "$pidfile" ] && [ -d "/proc/$(cat "$pidfile")" ]) && /etc/init.d/fastd stop
		fi
	fi
	exit 0
else
	echo "vpn-select: Hood file not found or empty!"
	exit 1
fi
