Automatically rebooting the DSL router when the Internet connection is lost

I had this script running some time ago in my wifi router (which was running TomatoUSB, a Linux-based firmware available for some Broadcom-based ethernet routers).

#!/bin/sh
while [ 1 ]; do
    nslookup google.com
    if [ $? -ne 0 ];
    then
        sleep 2
        ping -W 2 -c 1 8.8.8.8
        if [ $? -ne 0 ];
        then
            (sleep 1; echo admin;
             sleep 1; echo 1234;
             sleep 2; echo "reboot";
             sleep 3; echo "exit"
            ) | telnet 192.168.1.1
            sleep 300
        fi
    fi
    sleep 300
done

Basically, this scripts tries to resolve google.com. If that fails, tries to ping the Google DNS (8.8.8.8). If this fails too, tries to connect to 192.168.1.1 using admin/1234 as user/password and sends the reboot command. The same checks are done every 300 seconds (or 600 if the router has been rebooted). This worked on the ADSL routers provided by Telefónica and Jazztel in Spain some time ago.

A good thing of this script is that does not depend on expect; and is compatible with busybox if compiled with nslookup and telnet.