#!/usr/bin/perl
use lib '../include';
use nms;
#
#

my $username = '';
my $password = 'removed';

# Seconds to wait for connection
my $timeout = 15;


use warnings;
use strict;
use Switch;
use CGI;
use Net::Telnet;
use DBI;
use Data::Dumper;

# Grab from .htaccess-authentication
my $user = $ENV{'REMOTE_USER'};

my $dbh = nms::db_connect();
$dbh->{AutoCommit} = 0;

# Ugly casting, found not other way
my $sinsert = $dbh->prepare(	"INSERT INTO squeue 
				(gid, added, priority, addr, sysname, cmd, author)
				VALUES(?::text::int, now(), ?::text::int, ?::text::inet, ?, ?, ?)")
	or die "Could not prepare sinsert";
my $sgetip = $dbh->prepare("SELECT ip FROM switches WHERE sysname = ?")
	or die "Could not prepare sgetip";
my $sgid = $dbh->prepare("SELECT nextval('squeue_group_sequence') as gid");

# Send a command to switch and return the data recvied from the switch
sub switch_exec($$) {
	my ($cmd, $conn) = @_;

	# Send the command and get data from switch
	my @data = $conn->cmd($cmd);
	my @lines = ();
	foreach my $line (@data) {
		# Remove escape-7 sequence
		$line =~ s/\x1b\x37//g;
		push (@lines, $line);
	}

	return @lines;
}

sub switch_connect($) {
	my ($ip) = @_;

	my $conn = new Net::Telnet(	Timeout => $timeout,
					Errmode => 'return',
					Prompt => '/(es3024|e\d+\-\dsw)>/i');
	my $ret = $conn->open(	Host => $ip);
	if (!$ret || $ret != 1) {
		return (0);
	}
	# XXX: Just send the password as text, I did not figure out how to
	# handle authentication with only password through $conn->login().
	#$conn->login(	Prompt => '/password[: ]*$/i',
	#		Name => $password,
	#		Password => $password);
	$conn->cmd($password);
	# Get rid of banner
	$conn->get;
	return ($conn);
}

sub parse_range($) {
	my $switches = $_;
	my @range;

	my @rangecomma = split(/\s*,\s*/, $switches);
	foreach (@rangecomma) {
		my ($first, $drop1, $last, $drop2) = $_ =~ /(e\d+\-[123456])(sw)?\s*\-\s*(e\d+\-[123456])?(sw)?/;
		if (!defined($first) && $_ =~ /e\d+\-[123456]/) {
			$first = $_;
		}
		if (!defined($first)) {
			print "<font color=\"red\">Parse error in: $_</font><br>\n";
			next;
		}
		my ($rowstart, $placestart) = $first =~ /e(\d+)\-([123456])/;
		if (!defined($rowstart) || !defined($placestart)) {
			print "<font color=\"red\">Parse error in: $_</font><br>\n";
			next;
		}
		my ($rowend, $placeend);
		if (!defined($last)) {
			$rowend = $rowstart;
			$placeend = $placestart;
		}
		else {
			($rowend, $placeend) = $last =~ /e(\d+)\-([123456])/;
		}
		if (!defined($rowend) || !defined($placeend)) {
			print "<font color=\"red\">Parse error in: $_</font><br>\n";
			next;
		}
		#print "e $rowstart - $placestart to e $rowend - $placeend <br>\n";
		for (my $i = $rowstart; $i <= $rowend; $i++) {
			my $dostart;
			if ($rowstart != $i) {
				$dostart = 1;
			}
			else {
				$dostart = $placestart;
			}
			for (my $j = $dostart; $j <= 6; $j++) {
				last if ($i == $rowend && $j > $placeend);
				push(@range, "e$i-$j");
			}
		}
	}
#	foreach (@range) {
#		print ":: $_<br>\n";
#	}
	return @range;
}

sub get_addr_from_switchnum($) {
	my ($sysname) = @_;

	$sgetip->execute($sysname."sw");
	if ($sgetip->rows() < 1) {
		print "Could not get the ip for: ".$sysname."sw";
		return undef;
	}
	my $row = $sgetip->fetchrow_hashref();
	return $row->{'ip'};
}

my $cgi = new CGI;

print $cgi->header(-type=>'text/html');

print << "EOF";
<html>
  <head>
    <title>Switch managment</title>
  </head>
  <body>
  <p>Du er logget inn som: $user</p>
    <form method="POST" action="smanagement.pl">
    <table>
      <tr>
        <td>Alle switchene</td>
        <td><input type="radio" name="rangetype" value="all" /></td>
	<td></td>
	<td>Disabled</td>
      </tr>
      <tr>
        <td>Switch</td>
        <td><input type="radio" checked name="rangetype" value="switch" /></td>
        <td><input type="text" name="range" /></td>
        <td>e1-2, e3-3 - e10-2</td>
      </tr>
      <tr>
        <td>Rad</td>
        <td><input type="radio" name="rangetype" value="row" /></td>
        <td><input type="text" name="range" /></td>
        <td>1,3-5 (Disabled)</td>
      </tr>
       <tr>
        <td><hr /></td>
        <td><hr /></td>
        <td><hr /></td>
        <td><hr /></td>
      </tr>
      <tr>
	<td>Prioritet</td>
	<td></td>
	<td>
	  <select name="priority">
	    <option value="1">1 (lavest)</option>
	    <option value="2">2</option>
	    <option selected value="3">3</option>
	    <option value="4">4</option>
	    <option value="5">5 (høyest)</option>
	  </select>
	</td>
      </tr>
      <tr>
        <td>Kommando(er):</td>
        <td></td>
	<td><textarea name="cmd"></textarea></td>
	<td>En kommando per linje</td>
      </td>
      <tr>
        <td><hr /></td>
        <td><hr /></td>
        <td><hr /></td>
        <td><hr /></td>
      </tr>
    </table>
    <input type="submit" value="Execute!" /><br />
    </form>
EOF

print "<br />\n";

my @switches = ();
switch ($cgi->param('rangetype')) {
	case 'all' {
#		print "Sender `".$cgi->param('cmd')."` til alle switchene<br />";
		@switches = ();
		print "<font color=\"red\">Slått av!</font>\n";
	}
	case 'switch' {
#		print "Sender `".$cgi->param('cmd')."` til switchene `"
#		      .$cgi->param('range')."`.<br />";
		$_ = $cgi->param('range');
		@switches = parse_range($_);
	}
	case 'row' {
#		print "Sender `".$cgi->param('cmd')."` til radene `"
#		      .$cgi->param('range')."`.<br />";
#		print "This function does not work yet.";
#		$_ = $cgi->param('range');
#		@switches = &parse_row_range($_);
		@switches = ();
		print "<font color=\"red\">Slått av!</font>\n";
	}
}

my $gid;
if (@switches > 0) {
	$sgid->execute();
	my $row = $sgid->fetchrow_hashref();
	$gid = $row->{gid};
}

my $pri = $cgi->param('priority');

print "<pre>\n";
foreach my $switch (@switches) {
	my $addr = get_addr_from_switchnum($switch);
	if (!defined($addr)) {
		next;
	}
	print "$switch got addr $addr <br>\n";
	my @cmds = split(/[\n\r]+/, $cgi->param('cmd'));
	print "Queuing commands for $switch:\n";
	foreach my $cmd (@cmds) {
		my $result = $sinsert->execute($gid, $pri, $addr, $switch, $cmd, $user);
	#	my $result = 1;
		if (!$result) {
			print "\t<font color=\"red\">"
			       ."Could not execute query."
			       ."</font>\n";
			print "\t".$dbh->errstr."\n";
		}
		else {
			print "\tQueued: $cmd\n";
		}
	}
	print "\n";
}
$dbh->commit;
if (defined($gid)) {
	print "<a href=\"sshow.pl?action=showgid&gid=".$gid."\">Vis resultat</a>\n";
}
print "</pre>\n";

print << "EOF";
  </body>
</html>
EOF
