#!/usr/bin/perl
use strict;
use warnings;
use DBI;
use Getopt::Long;
use LWP::UserAgent;
{
	package RequestAgent;
	our @ISA = qw(LWP::UserAgent);

	sub new {
		return LWP::UserAgent::new(@_);
	}

	sub get_basic_credentials {
		return ("admin", "removed");
	}
}

# CONFIG
my $read = 0;
my $write = 0;
GetOptions ("read|r" => \$read, "write|w" => \$write);
my $target_mask = $ARGV[0] ? $ARGV[0] : 'e%-%sw';


# ACTION
my $dbh = DBI->connect("dbi:Pg:dbname=snmpfetch;host=violet.tg05.gathering.org",
                       "snmpfetch", "removed")
        or die "Couldn't connect to database";

my $sth = $dbh->prepare("SELECT sysname,ip FROM switches WHERE sysname LIKE ? ORDER BY ip");
$sth->execute($target_mask);

while (my ($sysname,$ip) = $sth->fetchrow_array) {
	my ($gw, $mgmnt);

	# Autodefine
	if ($ip =~ /(\d+\.\d+\.\d*)(\d)\.\d+/) {
		$gw = $1.$2.".1";
		$mgmnt = "90$2";
	} else {
		print "$sysname\t($ip):\tAieeh! IP parsing fuckup!\n";
		next;
	}

	# Define
	my $url = "http://$ip/Forms/rpip_1";
	my %shit = (
			"rpip_RpgDHCP" => "1",
			"rpip_IptIPAddr" => "$ip",
			"rpip_IptSubnetMask" => "255.255.255.0",
			"rpip_IptDefaultGateway" => "$gw",
			"rpip_IptDNS" => "0.0.0.0",
			"rpip_IptVID" => "$mgmnt",
			"rpip_HidBtnNum" => "1"
		   );

	# Check	
	my $found = 0;
	open(NMAP, "nmap -p80 $ip|");
	while(<NMAP>) {
		if(/^80\/tcp\s+open/) {
			$found = 1;
		}
	}
	if(!$found) {
		print "$sysname\t($ip):\tNo reply on port 80\n";
		next;
	}

	# Read
	if ($read) {
		print "$sysname\t($ip):\t";
		
		my $ua = RequestAgent->new;
		my $res = $ua->get("http://$ip/rpip.html");
		if ($res->is_success) {
			foreach (split("\n", $res->content)) {
				if (/.*rpip_IptDefaultGateway" .* VALUE="([^"]+)">/) {
					print "default route $1\n";
				}
			}
        	}  else {
			print $res->status_line, "\n";
		}
	}
	
	# Rape
	if ($write) {
		print "$sysname\t($ip):\t";
		
		my $ua = RequestAgent->new;
		my $res = $ua->post($url, \%shit);
		
		print $res->status_line, "\n";
	}
}
