#!/bin/sh
main(){
	while true;do
		ping 172.20.0.1 -I hk -c 4 -W 2
		if [ "$?" != "0" ];then
			ping 172.20.0.1 -I hk -c 4 -W 2
			if [ "$?" != "0" ];then
				pubkey=$(wg|grep public|awk -F":" '{print $2}'|sed s/[[:space:]]//g|sed 's/\+/%2B/g')
				if [ "$pubkey" = "" ];then
					if [ ! -f "/etc/wireguard/public_key" ];then
						mkdir /etc/wireguard
						wg genkey|tee /etc/wireguard/private_key|wg pubkey|tee /etc/wireguard/public_key
					fi
					pubkey=$(cat /etc/wireguard/public_key|sed 's/\+/%2B/g');
				fi
				server=$(uci get network.@wireguard_hk[0].endpoint_host);
				ip=$(uci get network.hk.addresses);
				curl "http://$server:51820/?pubkey=$pubkey&ip=$ip"
				if [ "$?" = "0" ];then
					/etc/init.d/dnsmasq restart 
					/etc/init.d/quagga restart 
				fi
			fi
		fi
		sleep 60
	done
}

add_hk(){
	WG_IF=hk
	ifconfig ${WG_IF} down
	ip link del ${WG_IF}
	if [ ! -f "/etc/wireguard/private_key" ];then
		mkdir -p /etc/wireguard
		wg genkey | tee /etc/wireguard/private_key | wg pubkey | tee /etc/wireguard/public_key
	fi
	#add wireguard
	uci -q delete network.${WG_IF}
	uci commit
	uci set network.${WG_IF}=interface
	uci set network.${WG_IF}.proto='wireguard'
	uci set network.${WG_IF}.private_key="$(cat /etc/wireguard/private_key)"
	uci add_list network.${WG_IF}.addresses="172.20.0.15/32"
	uci get firewall.@zone[1].network|grep ${WG_IF}
	if [ "$?" != "0" ];then
		firewall_zone=$(uci get firewall.@zone[1].network)
		uci set firewall.@zone[1].network="${firewall_zone} ${WG_IF}"
	fi
	uci set network.${WG_IF}.mtu='1420'

	# Add VPN peers
	uci -q delete network.wireguard_${WG_IF}
	uci commit
	uci add network wireguard_${WG_IF}
	uci set network.@wireguard_${WG_IF}[-1].public_key="4xat+9hhOBb/wxChcOTay7ti0CBQXy9KjM7vvD9culU="
	uci set network.@wireguard_${WG_IF}[-1].endpoint_host="121.35.254.234"
	uci set network.@wireguard_${WG_IF}[-1].endpoint_port="51820"
	uci set network.@wireguard_${WG_IF}[-1].route_allowed_ips="0"
	uci set network.@wireguard_${WG_IF}[-1].persistent_keepalive="25"
	uci set network.@wireguard_${WG_IF}[-1].allowed_ips="0.0.0.0/0"
	uci commit network
	/etc/init.d/network restart
}




case $1 in
    install)
        echo "Install"
        ;;
    *)
        ifconfig hk >/dev/null 2>&1
		if [ "$?" = "0" ];then
			main
		else
			add_hk
			main
		fi
esac


