Why to use such huge script?
Assuming you have two wan ports both masqueraded. For each port you have one default route, one with distance 12, second with distance 13.
Then you select some public ip that you want to check thru first gw. You need to set static route to it with distance 1. Also you set the static blackhole route to it with distance 99.
Then you set netwatch checking your testing ip address. When fails, you just change the distance 12 of the default route to 22 by netwatch in “down”:
/ip route set distance=22 [find distance=12];
if the checking ip is reachable you just set the route back by the same netwatch in “up”:
/ip route set distance=12 [find distance=22];
And that is all.
You can also do the same with second route or with whatever number of wan ports you want to failover.