#!/usr/bin/perl -w
use strict;
use Getopt::Std;
use Pod::Usage;
use Sysadm::Install qw(:all);
use Config::Patch;
use Buffalo::G54;
use X10::Home;
use Log::Log4perl 1.13 qw(:easy);

my @isps = qw(cable dsl);
my($switch_to) = @ARGV;

Log::Log4perl->easy_init($INFO);

if(! defined $switch_to) {
   pod2usage(
         "Specify what ISP to switch to");
}

if(! grep { $_ eq $switch_to }  @isps) {
   pod2usage("Unknown isp, use ",
             join(", ", @isps));
}

my $x10 = X10::Home->new();

my $P = password_read("Router password: ");

no strict 'refs';
eval { $switch_to->(); };
network_restart();

###########################################
sub dsl {
###########################################
 gateway_patch("192.168.10.1");
 $x10->send("bridge", "off");
 dhcp("on");
}

###########################################
sub cable {
###########################################
 gateway_patch("192.168.10.98");
 $x10->send("bridge", "on");
 dhcp("off");
 ALWAYS "Waiting for bridge to start up";
 sleep 20;
}

###########################################
sub network_restart {
###########################################
 tap "sudo", "/etc/rc.d/init.d/network",
     "restart";
}

###########################################
sub gateway_patch {
###########################################
   my($ip) = @_;

   my $patcher = Config::Patch->new(
       file => "/etc/sysconfig/network",
       key  => "isp-switch",
   );

   if($patcher->patched()) {
       # patched already? Remove old patch
       $patcher->remove();
   }

   $patcher->replace(qr(^GATEWAY=.*)m,
                     "GATEWAY=$ip");
}

###########################################
sub dhcp {
###########################################
   my($onoff) = @_;

   DEBUG "Setting dhcp to $onoff";

   my $b = Buffalo::G54->new();
   DEBUG "Connecting";
   $b->connect(password => $P);

   if(defined $onoff) {
       INFO "Setting DHCP to $onoff";
       $b->dhcp($onoff);
   }

   INFO "DHCP is now ", $b->dhcp() ?
                        "on" : "off";
}

__END__

=head1 NAME

   isp-switch - Cable or DSL?

=head1 SYNOPSIS

   isp-switch [dsl|cable]

=head1 DESCRIPTION

isp-switch switches between Comcast cable
and Pacbell DSL.

=head1 AUTHOR

2007, Mike Schilli <[email protected]>