#!/usr/bin/env bash
#Setup Wireguard VPN if config are available

WGVPN=/hive-config/wireguard
WGVPN_INSTALLED="/tmp/.wireguard-installed"
[ -f $WGVPN_INSTALLED ] && rm $WGVPN_INSTALLED

need_install=
dpkg -s wireguard-tools  > /dev/null 2>&1
[[ $? -ne 0 ]] && need_install="$need_install wireguard-tools"
dpkg -s iptables  > /dev/null 2>&1
[[ $? -ne 0 ]] && need_install="$need_install iptables"
if [[ ! -z $need_install ]]; then
	echo
	echo "Install $need_install packages."
	echo "Please wait..."
	apt update > /dev/null 2>&1
	apt install -y $need_install > /dev/null 2>&1
	update-inetd --disable tftp > /dev/null 2>&1
	echo "Done"
	echo
fi

#Search for client conf
conf=`find $WGVPN/ -iname '*.conf' -exec basename {} \; | head -n 1`
[[ -z $conf ]] && echo "No Wireguard VPN config found" && exit 1
echo "Wireguard VPN config $WGVPN/$conf"
dos2unix $WGVPN/$conf > /dev/null 2>&1
[ -f /etc/wireguard/wg0.conf ] && rm /etc/wireguard/wg0.conf
ln -sf $WGVPN/$conf /etc/wireguard/wg0.conf

source <(grep Address $WGVPN/$conf | tr -d ' ')

systemctl enable wg-quick@wg0

systemctl restart wg-quick@wg0

touch $WGVPN_INSTALLED

exitcode=1
#this is stupid, but we need to wait a bit for wg to setup
for i in {1..15}; do
	count=`echo $(hostname -I) | sed 's/ /\n/g' | wc -l`
	[[ $count > 1 ]] &&
		echo "One more interface came up" > /dev/tty1 &&
		echo "One more interface came up" &&
		exitcode=0 &&
		break
	echo "Waiting interface to come up... $i" > /dev/tty1
	echo "Waiting interface to come up... $i"
	sleep 1
	#If IP not added to interface in auto
	[[ $i = 5 ]] && ip -4 address add $Address dev wg0 #> /dev/null 2>&1
done


exit $exitcode