Failover for two (or more) Wireguard VPN

Hello! Help set the switch between the VPN Wireguard when one is not available, so that OpenWRT automatically switches to the other. I use Wireguard to protect all the traffic.

I wrote a short script that I use outside of OpenWrt but you can easily modify it a bit to fit the wg-framework on your router.

#!/bin/bash

handshake=$(wg | grep "latest handshake" | cut -d ":" -f2 | cut -d "," -f1)
pingtest=$(ping -c 3 www.heise.de | grep "time" | head -n 3)
wg1status=$(systemctl status wg-quick@wg1 | grep "Active: active")
wg2status=$(systemctl status wg-quick@wg2 | grep "Active: active")

if [[ $handshake == *"1 minute"* ]]; then
	echo "ok"
elif
	[[ -z $pingtest ]]; then
		if [[ -z $wg2status ]]; then
			wg-quick down wg1
			wg-quick up wg2
		elif
		       [[ -z $wg1status ]]; then	
			wg-quick down wg2
			wg-quick up wg1
		fi
fi

Since you don't have the wg-quick on your router, you can work with something like wg | grep wg | cut -d ":" -f2 to check wich interface is currently up and use it to fill $wgXstatus.
You may also change the $handshake test depending on your handshake settings.

Finally you can create a cronjob that runs the script every n minutes.