#!/usr/bin/perl
#
#

use warnings;
use strict;

use lib '../include';

use Net::Telnet::Cisco;
use Net::Ping;

use Data::Dumper;

#my $patchlist = "/home/eirikn/patchlist.txt";
#my $switches = "/home/eirikn/switches.txt";
my $patchlist = "/home/eirikn/patchlist.txt.eirik";
my $switches = "/home/eirikn/switches.txt.eirik";

BEGIN {
	require "../include/config.pm";
	eval {
		require "../include/config.local.pm";
	};
}

sub ios_getroute {
	my ($t, $net) = @_;

	$t->cmd("show ip route".($net ? " $net" : '')) or return 0;;
	
	return 1;
}

#my $ios_server = "noc-gw.net.tg07.gathering.org";
#my $vlannumber = 16;

#my $ios = nms::ios_connect($ios_server, $nms::config::ios_user, $nms::config::ios_pass)
#	or die "Unable to connect to cisco";



sub do_distro {
	my ($dip, $newip, $vlan) = @_;

	my $ios = Net::Telnet::Cisco->new(Host => $dip,
			Errmode => 'return',
			Prompt => '/[^\s\(]+(\([^\(]\)){0,1}[#>]/');
	$ios->login($nms::config::ios_user, $nms::config::ios_pass);
	$ios->enable;

#nms::ios_enable($ios);
#$ios->cmd();
#nms::ios_getroute($ios, "192.168.1.0");
#$ios->cmd("");

#nms::ios_close($ios);

# Disable paging
	$ios->cmd("terminal length 0");

#my @routes = $ios->cmd("show ip route");

	if (ios_getroute($ios, "192.168.1.0") == 1) {
		print "Already routed up 192.168.1.0/24\n" ;
		return;
	}

	$ios->cmd("conf t");
	$ios->cmd("int vlan $vlan");
	$ios->cmd("ip add 192.168.1.254 255.255.255.0 secondary");
	$ios->cmd("exit");
	$ios->cmd("exit");

	my $zyxeloldip = "192.168.1.1";

### Do things
## ZyxelNG connect

	my $p = Net::Ping->new();
	printf "Waiting for zyxel to come up...\n";
	while (1) {
		last if $p->ping($zyxeloldip);
		print "pinging...\n";
		sleep 1;
	}
	print "Zyxel is alive..\n";
	$p->close();

	system("perl ./zyxelng.pl 192.168.1.1 $newip");

####

	$ios->cmd("conf t");
	$ios->cmd("int vlan $vlan");
	$ios->cmd("no ip add 192.168.1.254 255.255.255.0 secondary");
	$ios->cmd("exit");
	$ios->cmd("exit");


	$ios->close();

}


## Collect switch ips

my %switchips;

open(SWITCHES, $switches) or die "Unable to open switches";
while(<SWITCHES>) {
	my ($ip, $net, $name) = split;

	print $name."\n";
	if ($name =~ /e\d+-\d/) {
		die "We only support /26 nets for now you wanted $net" if ($net ne "26");
		$switchips{$name} = $ip;
	}
}
close(SWITCHES);


open(PATCHLIST, $patchlist) or die "Unable to open patchlist";
while (<PATCHLIST>) {
	my ($switch, $distro, $port) = split;
	
	$switch =~ /e(\d+)-(\d)/;
	my ($row, $place) = ($1, $2);
	my $ipnet = $switchips{$switch};
	my $vlan = $row . $place;
	print "Switch: $switch, Distro: $distro, vlan: $vlan\n";
	print "Ip net: $ipnet\n";
	my ($first, $second, $third, $fourth) = split(/\./, $ipnet);
	my $ip = "$first.$second.$third.".(int($fourth)+2);
	print "Ip: $ip\n";
	my $dip = $distro.".net.tg07.gathering.org";

	do_distro($dip, $ip, $vlan);
#	my ($dip, $newip, $vlan) = @_;
}
close(PATCHLIST);





