#!/usr/bin/perl
# ipdb/cgi-bin/main.cgi
# Started munging from noc.vianet's old IPDB 04/22/2004
###
# SVN revision info
# $Date: 2005-06-17 20:08:35 +0000 (Fri, 17 Jun 2005) $
# SVN revision $Rev: 261 $
# Last update by $Author: kdeugau $
###

use strict;		
use warnings;	
use CGI::Carp qw(fatalsToBrowser);
use DBI;
use CommonWeb qw(:ALL);
use MyIPDB;
use POSIX qw(ceil);
use NetAddr::IP;

use Sys::Syslog;

openlog "IPDB","pid","local2";

# Collect the username from HTTP auth.  If undefined, we're in
# a test environment, or called without a username.
my $authuser;
if (!defined($ENV{'REMOTE_USER'})) {
  $authuser = '__temptest';
} else {
  $authuser = $ENV{'REMOTE_USER'};
}

syslog "debug", "$authuser active";

# Why not a global DB handle?  (And a global statement handle, as well...)
# Use the connectDB function, otherwise we end up confusing ourselves
my $ip_dbh;
my $sth;
my $errstr;
($ip_dbh,$errstr) = connectDB_My;
if (!$ip_dbh) {
  exitError("Database error: $errstr\n");
}
initIPDBGlobals($ip_dbh);

# Headerize!  Make sure we replace the $$EXTRA0$$ bit as needed.
printHeader('', ($IPDBacl{$authuser} =~ /a/ ?
	'<td align=right><a href="/ip/cgi-bin/main.cgi?action=assign">Add new assignment</a>' : ''
	));


# Global variables
my %webvar = parse_post();
cleanInput(\%webvar);


#main()

if(!defined($webvar{action})) {
  $webvar{action} = "<NULL>";	#shuts up the warnings.
}

if($webvar{action} eq 'index') {
  showSummary();
} elsif ($webvar{action} eq 'addmaster') {
  if ($IPDBacl{$authuser} !~ /a/) {
    printError("You shouldn't have been able to get here.  Access denied.");
  } else {
    open HTML, "<../addmaster.html";
    print while <HTML>;
  }
} elsif ($webvar{action} eq 'newmaster') {

  if ($IPDBacl{$authuser} !~ /a/) {
    printError("You shouldn't have been able to get here.  Access denied.");
  } else {

    my $cidr = new NetAddr::IP $webvar{cidr};

    print "<div type=heading align=center>Adding $cidr as master block....</div>\n";

    # Allow transactions, and raise an exception on errors so we can catch it later.
    # Use local to make sure these get "reset" properly on exiting this block
    local $ip_dbh->{AutoCommit} = 0;
    local $ip_dbh->{RaiseError} = 1;

    # Wrap the SQL in a transaction
    eval {
      $sth = $ip_dbh->prepare("insert into masterblocks values ('$webvar{cidr}')");
      $sth->execute;

# Unrouted blocks aren't associated with a city (yet).  We don't rely on this
# elsewhere though;  legacy data may have traps and pitfalls in it to break this.
# Thus the "routed" flag.

      $sth = $ip_dbh->prepare("insert into freeblocks (cidr,maskbits,city,routed)".
	" values ('$webvar{cidr}',".$cidr->masklen.",'<NULL>','n')");
      $sth->execute;

      # If we get here, everything is happy.  Commit changes.
      $ip_dbh->commit;
    }; # end eval

    if ($@) {
      carp "Transaction aborted because $@";
      eval { $ip_dbh->rollback; };
      syslog "err", "Could not add master block '$webvar{cidr}' to database: '$@'";
      printError("Could not add master block $webvar{cidr} to database: $@");
    } else {
      print "<div type=heading align=center>Success!</div>\n";
      syslog "info", "$authuser added master block $webvar{cidr}";
    }

  } # ACL check

} # end add new master

elsif($webvar{action} eq 'showmaster') {
  showMaster();
}
elsif($webvar{action} eq 'showrouted') {
  showRBlock();
}
elsif($webvar{action} eq 'listpool') {
  listPool();
}

# Not modified or added;  just shuffled
elsif($webvar{action} eq 'assign') {
  assignBlock();
}
elsif($webvar{action} eq 'confirm') {
  confirmAssign();
}
elsif($webvar{action} eq 'insert') {
  insertAssign();
}
elsif($webvar{action} eq 'edit') {
  edit();
}
elsif($webvar{action} eq 'update') {
  update();
}
elsif($webvar{action} eq 'delete') {
  remove();
}
elsif($webvar{action} eq 'finaldelete') {
  finalDelete();
}

# Default is an error.  It shouldn't be possible to easily get here.
# The only way I can think of offhand is to just call main.cgi bare-
# which is not in any way guaranteed to provide anything useful.
else {
  my $rnd = rand 500;
  my $boing = sprintf("%.2f", rand 500);
  my @excuses = ("Aether cloudy.  Ask again later.","The gods are unhappy with your sacrifice.",
	"Because one of it's legs are both the same", "*wibble*",
	"Hey! Stop pushing my buttons!", "I ain't done nuttin'", "9",
	"8", "9", "10", "11", "12", "13", "14", "15", "16", "17");
  printAndExit("Error $boing:  ".$excuses[$rnd/30.0]);
}
## Finally! Done with that NASTY "case" emulation!



# Clean up IPDB globals, DB handle, etc.
finish($ip_dbh);

print qq(<div align=right style="position: absolute; right: 30px;">).
	qq(<a href="/ip/cgi-bin/admin.cgi">Admin tools</a></div><br>\n)
	if $IPDBacl{$authuser} =~ /A/;

# We print the footer here, so we don't have to do it elsewhere.
printFooter;
# Just in case something waaaayyy down isn't in place
# properly... we exit explicitly.
exit;



# args are: a reference to an array with the row to be printed and the 
# class(stylesheet) to use for formatting.
# if ommitting the class - call the sub as &printRow(\@array)
sub printRow {
  my ($rowRef,$class) = @_;

  if (!$class) {
    print "<tr>\n";
  } else {
    print "<tr class=\"$class\">\n";
  }

ELEMENT:  foreach my $element (@$rowRef) {
    if (!defined($element)) {
      print "<td></td>\n";
      next ELEMENT;
    }
    $element =~ s|\n|</br>|g;
    print "<td>$element</td>\n";
  }
  print "</tr>";
} # printRow


# Prints table headings.  Accepts any number of arguments;
# each argument is a table heading.
sub startTable {
  print qq(<center><table width="98%" cellspacing="0" class="center"><tr>);

  foreach(@_) {
    print qq(<td class="heading">$_</td>);
  }
  print "</tr>\n";
} # startTable


# Initial display:  Show master blocks with total allocated subnets, total free subnets
sub showSummary {

  startTable('Master netblock', 'Routed netblocks', 'Allocated netblocks',
	'Free netblocks', 'Largest free block');

  my %allocated;
  my %free;
  my %routed;
  my %bigfree;

  # Count the allocations.
  $sth = $ip_dbh->prepare("select count(*) from allocations where cidr <<= ?");
  foreach my $master (@masterblocks) {
    $sth->execute("$master");
    $sth->bind_columns(\$allocated{"$master"});
    $sth->fetch();
  }

  # Count routed blocks
  $sth = $ip_dbh->prepare("select count(*) from routed where cidr <<= ?");
  foreach my $master (@masterblocks) {
    $sth->execute("$master");
    $sth->bind_columns(\$routed{"$master"});
    $sth->fetch();
  }

  # Count the free blocks.
  $sth = $ip_dbh->prepare("select count(*) from freeblocks where cidr <<= ? and ".
	"(routed='y' or routed='n')");
  foreach my $master (@masterblocks) {
    $sth->execute("$master");
    $sth->bind_columns(\$free{"$master"});
    $sth->fetch();
  }

  # Find the largest free block in each master
  $sth = $ip_dbh->prepare("select maskbits from freeblocks where cidr <<= ? and ".
	"(routed='y' or routed='n') order by maskbits limit 1");
  foreach my $master (@masterblocks) {
    $sth->execute("$master");
    $sth->bind_columns(\$bigfree{"$master"});
    $sth->fetch();
  }

  # Print the data.
  my $count=0;
  foreach my $master (@masterblocks) {
    my @row = ("<a href=\"/ip/cgi-bin/main.cgi?action=showmaster&block=$master\">$master</a>",
	$routed{"$master"}, $allocated{"$master"}, $free{"$master"}, 
	( ($bigfree{"$master"} eq '') ? ("&lt;NONE&gt;") : ("/".$bigfree{"$master"}) )
	);

    printRow(\@row, 'color1' ) if($count%2==0);
    printRow(\@row, 'color2' ) if($count%2!=0);
    $count++;
  }
  print "</table>\n";
  if ($IPDBacl{$authuser} =~ /a/) {
    print qq(<a href="/ip/cgi-bin/main.cgi?action=addmaster">Add new master block</a><br><br>\n);
  }
  print "Note:  Free blocks noted here include both routed and unrouted blocks.\n";

} # showSummary


# Display detail on master
# Alrighty then!  We're showing routed blocks within a single master this time.
# We should be able to steal code from showSummary(), and if I'm really smart
# I'll figger a way to munge the two together.  (Once I've done that, everything
# else should follow.  YMMV.)
sub showMaster {

  print qq(<center><div class="heading">Summarizing routed blocks for ).
	qq($webvar{block}:</div></center><br>\n);

  my %allocated;
  my %free;
  my %routed;
  my %bigfree;

  my $master = new NetAddr::IP $webvar{block};
  my @localmasters;

  # Fetch only the blocks relevant to this master
  $sth = $ip_dbh->prepare("select cidr,city from routed where cidr <<= '$master' order by cidr");
  $sth->execute();

  my $i=0;
  while (my @data = $sth->fetchrow_array()) {
    my $cidr = new NetAddr::IP $data[0];
    $localmasters[$i++] = $cidr;
    $free{"$cidr"} = 0;
    $allocated{"$cidr"} = 0;
    $bigfree{"$cidr"} = 128;
    # Retain the routing destination
    $routed{"$cidr"} = $data[1];
  }

  # Check if there were actually any blocks routed from this master
  if ($i > 0) {
    startTable('Routed block','Routed to','Allocated blocks',
	'Free blocks','Largest free block');

    # Count the allocations
    $sth = $ip_dbh->prepare("select count(*) from allocations where cidr <<= ?");
    foreach my $master (@localmasters) {
      $sth->execute("$master");
      $sth->bind_columns(\$allocated{"$master"});
      $sth->fetch();
    }

    # Count the free blocks.
    $sth = $ip_dbh->prepare("select count(*) from freeblocks where cidr <<= ? and ".
	"(routed='y' or routed='n')");
    foreach my $master (@localmasters) {
      $sth->execute("$master");
      $sth->bind_columns(\$free{"$master"});
      $sth->fetch();
    }

    # Get the size of the largest free block
    $sth = $ip_dbh->prepare("select maskbits from freeblocks where cidr <<= ? and ".
	"(routed='y' or routed='n') order by maskbits limit 1");
    foreach my $master (@localmasters) {
      $sth->execute("$master");
      $sth->bind_columns(\$bigfree{"$master"});
      $sth->fetch();
    }

    # Print the data.
    my $count=0;
    foreach my $master (@localmasters) {
      my @row = ("<a href=\"/ip/cgi-bin/main.cgi?action=showrouted&block=$master\">$master</a>",
	$routed{"$master"}, $allocated{"$master"},
	$free{"$master"},
	( ($bigfree{"$master"} eq 128) ? ("&lt;NONE&gt;") : ("/".$bigfree{"$master"}) )
      );
      printRow(\@row, 'color1' ) if($count%2==0);
      printRow(\@row, 'color2' ) if($count%2!=0);
      $count++;
    }
  } else {
    # If a master block has no routed blocks, then by definition it has no
    # allocations, and can be deleted.
    print qq(<hr width="60%"><center><div class="heading">No allocations in ).
        qq($master.</div>\n).
	($IPDBacl{$authuser} =~ /d/ ?
	        qq(<form action="/ip/cgi-bin/main.cgi" method=POST>\n).
	        qq(<input type=hidden name=action value="delete">\n).
	        qq(<input type=hidden name=block value="$master">\n).
	        qq(<input type=hidden name=alloctype value="mm">\n).
	        qq(<input type=submit value=" Remove this master ">\n).
	        qq(</form></center>\n) :
		'');

  } # end check for existence of routed blocks in master

  print qq(</table>\n<hr width="60%">\n).
	qq(<center><div class="heading">Unrouted blocks in $master:</div></center><br>\n);

  startTable('Netblock','Range');

  # Snag the free blocks.
  my $count = 0;
  $sth = $ip_dbh->prepare("select cidr from freeblocks where cidr <<='$master' and ".
	"routed='n' order by cidr");
  $sth->execute();
  while (my @data = $sth->fetchrow_array()) {
    my $cidr = new NetAddr::IP $data[0];
    my @row = ("$cidr", $cidr->range);
    printRow(\@row, 'color1' ) if($count%2==0);
    printRow(\@row, 'color2' ) if($count%2!=0);
    $count++;
  }

  print "</table>\n";
} # showMaster


# Display details of a routed block
# Alrighty then!  We're showing allocations within a routed block this time.
# We should be able to steal code from showSummary() and showMaster(), and if
# I'm really smart I'll figger a way to munge all three together.  (Once I've
# done that, everything else should follow.  YMMV.
# This time, we check the database before spewing, because we may
# not have anything useful to spew.
sub showRBlock {

  my $master = new NetAddr::IP $webvar{block};

  $sth = $ip_dbh->prepare("select city from routed where cidr='$master'");
  $sth->execute;
  my @data = $sth->fetchrow_array;

  print qq(<center><div class="heading">Summarizing allocated blocks for ).
	qq($master ($data[0]):</div></center><br>\n);

  startTable('CIDR allocation','Customer Location','Type','CustID','Description/Name');

  # Snag the allocations for this block
  $sth = $ip_dbh->prepare("select cidr,city,type,custid,description".
	" from allocations where cidr <<= '$master' order by cidr");
  $sth->execute();

  my $count=0;
  while (my @data = $sth->fetchrow_array()) {
    # cidr,city,type,custid,description, as per the SELECT
    my $cidr = new NetAddr::IP $data[0];

    # Clean up extra spaces that are borking things.
#    $data[2] =~ s/\s+//g;

    # Prefix subblocks with "Sub "
    my @row = ( (($data[2] =~ /^.r$/) ? 'Sub ' : '').
	qq(<a href="/ip/cgi-bin/main.cgi?action=edit&block=$data[0]">$data[0]</a>),
	$data[1], $disp_alloctypes{$data[2]}, $data[3], $data[4]);
    # If the allocation is a pool, allow listing of the IPs in the pool.
    if ($data[2] =~ /^.[pd]$/) {
      $row[0] .= ' &nbsp; <a href="/ip/cgi-bin/main.cgi?action=listpool'.
	"&pool=$data[0]\">List IPs</a>";
    }

    printRow(\@row, 'color1') if ($count%2 == 0);
    printRow(\@row, 'color2') if ($count%2 != 0);
    $count++;
  }

  print "</table>\n";

  # If the routed block has no allocations, by definition it only has
  # one free block, and therefore may be deleted.
  if ($count == 0) {
    print qq(<hr width="60%"><center><div class="heading">No allocations in ).
	qq($master.</div></center>\n).
	($IPDBacl{$authuser} =~ /d/ ?
		qq(<form action="/ip/cgi-bin/main.cgi" method=POST>\n).
		qq(<input type=hidden name=action value="delete">\n).
		qq(<input type=hidden name=block value="$master">\n).
		qq(<input type=hidden name=alloctype value="rm">\n).
		qq(<input type=submit value=" Remove this block ">\n).
		qq(</form>\n) :
		'');
  }

  print qq(<hr width="60%">\n<center><div class="heading">Free blocks within routed ).
	qq(submaster $master</div></center>\n);

  startTable('CIDR block','Range');

  # Snag the free blocks.  We don't really *need* to be pedantic about avoiding
  # unrouted free blocks, but it's better to let the database do the work if we can.
  $count = 0;
  $sth = $ip_dbh->prepare("select cidr,routed from freeblocks where cidr <<= '$master'".
	" order by cidr");
  $sth->execute();
  while (my @data = $sth->fetchrow_array()) {
    # cidr,routed
    my $cidr = new NetAddr::IP $data[0];
    # Include some HairyPerl(TM) to prefix subblocks with "Sub "
    my @row = ((($data[1] ne 'y' && $data[1] ne 'n') ? 'Sub ' : '').
	($IPDBacl{$authuser} =~ /a/ ? qq(<a href="/ip/cgi-bin/main.cgi?action=assign&block=$cidr&fbtype=$data[1]">$cidr</a>) : $cidr),
	$cidr->range);
    printRow(\@row, 'color1') if ($count%2 == 0);
    printRow(\@row, 'color2') if ($count%2 != 0);
    $count++;
  }

  print "</table>\n";
} # showRBlock


# List the IPs used in a pool
sub listPool {

  my $cidr = new NetAddr::IP $webvar{pool};

  my ($pooltype,$poolcity);

  # Snag pool info for heading
  $sth = $ip_dbh->prepare("select type,city from allocations where cidr='$cidr'");
  $sth->execute;
  $sth->bind_columns(\$pooltype, \$poolcity);
  $sth->fetch() || carp $sth->errstr;

  print qq(<center><div class="heading">Listing pool IPs for $cidr<br>\n).
	qq(($disp_alloctypes{$pooltype} in $poolcity)</div></center><br>\n);
  # Only display net/gw/bcast if it's a "real" netblock and not a PPP(oE) lunacy
  if ($pooltype =~ /^.d$/) {
    print qq(<div class="indent"><b>Reserved IPs:</b><br>\n);
    print qq(<div class="indent"><table><tr class=color1><td>Network IP:</td><td>).
	$cidr->addr."</td></tr>\n";
    $cidr++;
    print "<tr class=color2><td>Gateway:</td><td>".$cidr->addr."</td></tr>\n";
    $cidr--;  $cidr--;
    print "<tr class=color1><td>Broadcast:</td><td>".$cidr->addr."</td></tr>\n".
	"<tr><td>Netmask:</td><td>".$cidr->mask."</td></tr>\n".
	"</table></div></div>\n";
  }

# probably have to add an "edit IP allocation" link here somewhere.

  startTable('IP','Customer ID','Available?','Description','');
  $sth = $ip_dbh->prepare("select ip,custid,available,description,type".
	" from poolips where pool='$webvar{pool}' order by ip");
  $sth->execute;
  my $count = 0;
  while (my @data = $sth->fetchrow_array) {
    # pool,ip,custid,city,ptype,available,notes,description,circuitid
    # ip,custid,available,description,type
    # If desc is "null", make it not null.  <g>
    if ($data[3] eq '') {
      $data[3] = '&nbsp;';
    }
    # Some nice hairy Perl to decide whether to allow unassigning each IP
    #   -> if $data[2] (aka poolips.available) == 'n' then we print the unassign link
    #	   else we print a blank space
    my @row = ( qq(<a href="/ip/cgi-bin/main.cgi?action=edit&block=$data[0]">$data[0]</a>),
	$data[1],$data[2],$data[3],
	( (($data[2] eq 'n') && ($IPDBacl{$authuser} =~ /d/)) ?
	  ("<a href=\"/ip/cgi-bin/main.cgi?action=delete&block=$data[0]&".
	   "alloctype=$data[4]\">Unassign this IP</a>") :
	  ("&nbsp;") )
	);
    printRow(\@row, 'color1') if($count%2==0);
    printRow(\@row, 'color2') if($count%2!=0);
    $count++;
  }
  print "</table>\n";

} # end listPool


# Show "Add new allocation" page.  Note that the actual page may
# be one of two templates, and the lists come from the database.
sub assignBlock {

  if ($IPDBacl{$authuser} !~ /a/) {
    printError("You shouldn't have been able to get here.  Access denied.");
    return;
  }

  my $html;

  # New special case- block to assign is specified
  if ($webvar{block} ne '') {
    open HTML, "../fb-assign.html"
	or croak "Could not open fb-assign.html: $!";
    $html = join('',<HTML>);
    close HTML;
    my $block = new NetAddr::IP $webvar{block};
    $html =~ s|\$\$BLOCK\$\$|$block|g;
    $html =~ s|\$\$MASKBITS\$\$|$block->masklen|;
    my $typelist = '';

    # This is a little dangerous, as it's *theoretically* possible to
    # get fbtype='n' (aka a non-routed freeblock).  However, should
    # someone manage to get there, they get what they deserve.
    if ($webvar{fbtype} ne 'y') {
      # Snag the type of the block from the database.  We have no
      # convenient way to pass this in from the calling location.  :/
      $sth = $ip_dbh->prepare("select type from allocations where cidr >>='$block'");
      $sth->execute;
      my @data = $sth->fetchrow_array;
      $data[0] =~ s/c$/r/;	# Munge the type into the correct form
      $typelist = "$list_alloctypes{$data[0]}<input type=hidden name=alloctype value=$data[0]>\n";
    } else {
      $typelist .= qq(<select name="alloctype">\n);
      $sth = $ip_dbh->prepare("select type,listname from alloctypes where listorder < 500 ".
	"and type not like '_i' and type not like '_r' order by listorder");
      $sth->execute;
      my @data = $sth->fetchrow_array;
      $typelist .= "<option value='$data[0]' selected>$data[1]</option>\n";
      while (my @data = $sth->fetchrow_array) {
        $typelist .= "<option value='$data[0]'>$data[1]</option>\n";
      }
      $typelist .= "</select>\n";
    }
    $html =~ s|\$\$TYPELIST\$\$|$typelist|g;
  } else {
    open HTML, "../assign.html"
	or croak "Could not open assign.html: $!";
    $html = join('',<HTML>);
    close HTML;
    my $masterlist = "<select name=allocfrom><option selected>-</option>\n";
    foreach my $master (@masterblocks) {
      $masterlist .= "<option>$master</option>\n";
    }
    $masterlist .= "</select>\n";
    $html =~ s|\$\$MASTERLIST\$\$|$masterlist|g;
    my $pops = '';
    foreach my $pop (@poplist) {
      $pops .= "<option>$pop</option>\n";
    }
    $html =~ s|\$\$POPLIST\$\$|$pops|g;
    my $typelist = '';
    $sth = $ip_dbh->prepare("select type,listname from alloctypes where listorder < 900 order by listorder");
    $sth->execute;
    my @data = $sth->fetchrow_array;
    $typelist .= "<option value='$data[0]' selected>$data[1]</option>\n";
    while (my @data = $sth->fetchrow_array) {
      $typelist .= "<option value='$data[0]'>$data[1]</option>\n";
    }
    $html =~ s|\$\$TYPELIST\$\$|$typelist|g;
  }
  my $cities = '';
  foreach my $city (@citylist) {
    $cities .= "<option>$city</option>\n";
  }
  $html =~ s|\$\$ALLCITIES\$\$|$cities|g;

  print $html;

} # assignBlock


# Take info on requested IP assignment and see what we can provide.
sub confirmAssign {
  if ($IPDBacl{$authuser} !~ /a/) {
    printError("You shouldn't have been able to get here.  Access denied.");
    return;
  }

  my $cidr;
  my $alloc_from;

  # Going to manually validate some items.
  # custid and city are automagic.
  return if !validateInput();

# Several different cases here.
# Static IP vs netblock
#  + Different flavours of static IP
#  + Different flavours of netblock

  if ($webvar{alloctype} =~ /^.i$/) {
    my ($base,undef) = split //, $webvar{alloctype};	# split into individual chars
    my ($sql,$city);
    # Check for pools in Subury, North Bay, or Toronto if DSL or server pool.
    # Anywhere else is invalid and shouldn't be in the db in the first place.
    # ... aside from #^%#$%#@#^%^^!!!! legacy data.  GRRR.
    # Note that we want to retain the requested city to relate to customer info.
    if ($base =~ /^[ds]$/) {
      $city = "(allocations.city='Sudbury' or allocations.city='North Bay' or ".
	"allocations.city='Toronto')";
    } else {
      $city = "allocations.city='$webvar{pop}'";
    }

# Ewww.  But it works.
    $sth = $ip_dbh->prepare("SELECT (SELECT city FROM allocations WHERE cidr=poolips.pool), ".
	"poolips.pool, COUNT(*) FROM poolips,allocations WHERE poolips.available='y' AND ".
	"poolips.pool=allocations.cidr AND $city AND poolips.type LIKE '".$base."_' ".
	"GROUP BY pool");
    $sth->execute;
    my $optionlist;
    while (my @data = $sth->fetchrow_array) {
      # city,pool cidr,free IP count
      if ($data[2] > 0) {
        $optionlist .= "<option value='$data[1]'>$data[1] [$data[2] free IP(s)] in $data[0]</option>\n";
      }
    }
    $cidr = "Single static IP";
    $alloc_from = "<select name=alloc_from>".$optionlist."</select>\n";

  } else { # end show pool options

    if ($webvar{fbassign} eq 'y') {
      $cidr = new NetAddr::IP $webvar{block};
      $webvar{maskbits} = $cidr->masklen;
    } else { # done with direct freeblocks assignment

      if (!$webvar{maskbits}) {
        printError("Please specify a CIDR mask length.");
	return;
      }
      my $sql;
      my $city;
      my $failmsg;
      if ($webvar{alloctype} eq 'rm') {
        if ($webvar{allocfrom} ne '-') {
	  $sql = "select * from freeblocks where maskbits<=$webvar{maskbits} and routed='n'".
		" and cidr <<= '$webvar{allocfrom}' order by maskbits desc";
	} else {
	  $sql = "select * from freeblocks where maskbits<=$webvar{maskbits} and routed='n'".
		" order by maskbits desc";
	}
	$failmsg = "No suitable free block found.<br>\nWe do not have a free".
	  " routeable block of that size.<br>\nYou will have to either route".
	  " a set of smaller netblocks or a single smaller netblock.";
      } else {
##fixme
# This section needs serious Pondering.
	# Pools of most types get assigned to the POP they're "routed from"
	# This includes WAN blocks and other netblock "containers"
	# This does NOT include cable pools.
	if ($webvar{alloctype} =~ /^.[pc]$/) {
	  if (($webvar{city} !~ /^(Sudbury|North Bay|Toronto)$/) && ($webvar{alloctype} eq 'dp')) {
	    printError("You must chose Sudbury, North Bay, or Toronto for DSL pools.");
	    return;
	  }
	  $city = $webvar{city};
	  $failmsg = "No suitable free block found.<br>\nYou will have to route another".
	    " superblock from one of the<br>\nmaster blocks in Sudbury or chose a smaller".
	    " block size for the pool.";
	} else {
	  $city = $webvar{pop};
	  $failmsg = "No suitable free block found.<br>\nYou will have to route another".
	    " superblock to $webvar{pop}<br>\nfrom one of the master blocks in Sudbury or".
	    " chose a smaller blocksize.";
	}
	if ($webvar{allocfrom} ne '-') {
	  $sql = "select cidr from freeblocks where city='$city' and maskbits<=$webvar{maskbits}".
		" and cidr <<= '$webvar{allocfrom}' and routed='".
		(($webvar{alloctype} =~ /^(.)r$/) ? "$1" : 'y')."' order by maskbits desc,cidr";
	} else {
	  $sql = "select cidr from freeblocks where city='$city' and maskbits<=$webvar{maskbits}".
		" and routed='".(($webvar{alloctype} =~ /^(.)r$/) ? "$1" : 'y').
		"' order by maskbits desc,cidr";
	}
      }
      $sth = $ip_dbh->prepare($sql);
      $sth->execute;
      my @data = $sth->fetchrow_array();
      if ($data[0] eq "") {
	printError($failmsg);
	return;
      }
      $cidr = new NetAddr::IP $data[0];
    } # check for freeblocks assignment or IPDB-controlled assignment

    $alloc_from = qq($cidr<input type=hidden name=alloc_from value="$cidr">);

    # If the block to be allocated is smaller than the one we found,
    # figure out the "real" block to be allocated.
    if ($cidr->masklen() ne $webvar{maskbits}) {
      my $maskbits = $cidr->masklen();
      my @subblocks;
      while ($maskbits++ < $webvar{maskbits}) {
	@subblocks = $cidr->split($maskbits);
      }
      $cidr = $subblocks[0];
    }
  } # if ($webvar{alloctype} =~ /^.i$/)

  open HTML, "../confirm.html"
	or croak "Could not open confirm.html: $!";
  my $html = join '', <HTML>;
  close HTML;

### gotta fix this in final
  # Stick in customer info as necessary - if it's blank, it just ends
  # up as blank lines ignored in the rendering of the page
	my $custbits;
  $html =~ s|\$\$CUSTBITS\$\$|$custbits|g;
###

  # Stick in the allocation data
  $html =~ s|\$\$ALLOC_TYPE\$\$|$webvar{alloctype}|g;
  $html =~ s|\$\$TYPEFULL\$\$|$disp_alloctypes{$webvar{alloctype}}|g;
  $html =~ s|\$\$ALLOC_FROM\$\$|$alloc_from|g;
  $html =~ s|\$\$CIDR\$\$|$cidr|g;
  $webvar{city} = desanitize($webvar{city});
  $html =~ s|\$\$CITY\$\$|$webvar{city}|g;
  $html =~ s|\$\$CUSTID\$\$|$webvar{custid}|g;
  $webvar{circid} = desanitize($webvar{circid});
  $html =~ s|\$\$CIRCID\$\$|$webvar{circid}|g;
  $webvar{desc} = desanitize($webvar{desc});
  $html =~ s|\$\$DESC\$\$|$webvar{desc}|g;
  $webvar{notes} = desanitize($webvar{notes});
  $html =~ s|\$\$NOTES\$\$|$webvar{notes}|g;
  $html =~ s|\$\$ACTION\$\$|insert|g;

  print $html;

} # end confirmAssign


# Do the work of actually inserting a block in the database.
sub insertAssign {
  if ($IPDBacl{$authuser} !~ /a/) {
    printError("You shouldn't have been able to get here.  Access denied.");
    return;
  }
  # Some things are done more than once.
  return if !validateInput();

  # $code is "success" vs "failure", $msg contains OK for a
  # successful netblock allocation, the IP allocated for static
  # IP, or the error message if an error occurred.
  my ($code,$msg) = allocateBlock($ip_dbh, $webvar{fullcidr}, $webvar{alloc_from},
	$webvar{custid}, $webvar{alloctype}, $webvar{city}, $webvar{desc}, $webvar{notes},
	$webvar{circid});

  if ($code eq 'OK') {
    if ($webvar{alloctype} =~ /^.i$/) {
      print qq(<div class="center"><div class="heading">The IP $msg has been allocated to customer $webvar{custid}</div></div>);
      # Notify tech@example.com
#      mailNotify('tech@example.com',"ADDED: $disp_alloctypes{$webvar{alloctype}} allocation",
#	"$disp_alloctypes{$webvar{alloctype}} $msg allocated to customer $webvar{custid}\n".
#	"Description: $webvar{desc}\n\nAllocated by: $authuser\n");
    } else {
      print qq(<div class="center"><div class="heading">The block $webvar{fullcidr} was ).
	"sucessfully added as: $disp_alloctypes{$webvar{alloctype}}</div></div>";
    }
    syslog "notice", "$authuser allocated '$webvar{fullcidr}' to '$webvar{custid}' as ".
	"'$webvar{alloctype}' ($msg)";
  } else {
    syslog "err", "Allocation of '$webvar{fullcidr}' to '$webvar{custid}' as ".
	"'$webvar{alloctype}' by $authuser failed: '$msg'";
    printError("Allocation of $webvar{fullcidr} as '$disp_alloctypes{$webvar{alloctype}}'".
	" failed:<br>\n$msg\n");
  }

} # end insertAssign()


# Does some basic checks on common input data to make sure nothing
# *really* weird gets in to the database through this script.
# Does NOT do complete input validation!!!
sub validateInput {
  if ($webvar{city} eq '-') {
    printError("Please choose a city.");
    return;
  }

  # Alloctype check.
  chomp $webvar{alloctype};
  if (!grep /$webvar{alloctype}/, keys %disp_alloctypes) {
    # Danger! Danger!  alloctype should ALWAYS be set by a dropdown.  Anyone
    # managing to call things in such a way as to cause this deserves a cryptic error.
    printError("Invalid alloctype");
    return;
  }

  # CustID check
  # We have different handling for customer allocations and "internal" or "our" allocations
  if ($def_custids{$webvar{alloctype}} eq '') {
    if (!$webvar{custid}) {
      printError("Please enter a customer ID.");
      return;
    }
    if ($webvar{custid} !~ /^(?:\d{10}|\d{7}|STAFF|TEMP)(?:-\d\d?)?$/) {
      printError("Please enter a valid customer ID- this must be a 7- or 10-digit number, or STAFF for static IPs for staff.");
      return;
    }
    print "<!-- [ In validateInput().  Insert customer ID cross-check here. ] -->\n";
  } else {
    # New!  Improved!  And now Loaded From The Database!!
    $webvar{custid} = $def_custids{$webvar{alloctype}};
  }

  # Check POP location
  my $flag;
  if ($webvar{alloctype} eq 'rm') {
    $flag = 'for a routed netblock';
    foreach (@poplist) {
      if (/^$webvar{city}$/) {
	$flag = 'n';
	last;
      }
    }
  } else {
    $flag = 'n';
    if ($webvar{pop} =~ /^-$/) {
      $flag = 'to route the block from/through';
    }
  }
  if ($flag ne 'n') {
    printError("Please choose a valid POP location $flag.  Valid ".
	"POP locations are currently:<br>\n".join (" - ", @poplist));
    return;
  }

  return 'OK';
} # end validateInput


# Displays details of a specific allocation in a form
# Allows update/delete
# action=edit
sub edit {

  my $sql;

  # Two cases:  block is a netblock, or block is a static IP from a pool
  # because I'm lazy, we'll try to make the SELECT's bring out identical)ish) data
  if ($webvar{block} =~ /\/32$/) {
    $sql = "select ip,custid,type,city,circuitid,description,notes,modifystamp from poolips where ip='$webvar{block}'";
  } else {
    $sql = "select cidr,custid,type,city,circuitid,description,notes,modifystamp from allocations where cidr='$webvar{block}'"
  }

  # gotta snag block info from db
  $sth = $ip_dbh->prepare($sql);
  $sth->execute;
  my @data = $sth->fetchrow_array;

  # Clean up extra whitespace on alloc type
  $data[2] =~ s/\s//;

  open (HTML, "../editDisplay.html")
	or croak "Could not open editDisplay.html :$!";
  my $html = join('', <HTML>);

  # We can't let the city be changed here;  this block is a part of
  # a larger routed allocation and therefore by definition can't be moved.
  # block and city are static.
##fixme
# Needs thinking.  Have to allow changes to city to correct errors, no?
  $html =~ s/\$\$BLOCK\$\$/$webvar{block}/g;

  if ($IPDBacl{$authuser} =~ /c/) {
    $html =~ s/\$\$CUSTID\$\$/<input type=text name=custid value="$data[1]" maxlength=15 class="regular">/;

# Screw it.  Changing allocation types gets very ugly VERY quickly- especially
# with the much longer list of allocation types.
# We'll just show what type of block it is.

# this has now been Requested, so here goes.

##fixme The check here should be built from the database
    if ($data[2] =~ /^.[ne]$/) {
      # Block that can be changed
      my $blockoptions = "<select name=alloctype><option".
	(($data[2] eq 'me') ? ' selected' : '') ." value='me'>Dialup netblock</option>\n<option".
	(($data[2] eq 'de') ? ' selected' : '') ." value='de'>Dynamic DSL netblock</option>\n<option".
	(($data[2] eq 'ce') ? ' selected' : '') ." value='ce'>Dynamic cable netblock</option>\n<option".
	(($data[2] eq 'we') ? ' selected' : '') ." value='we'>Dynamic wireless netblock</option>\n<option".
	(($data[2] eq 'cn') ? ' selected' : '') ." value='cn'>Customer netblock</option>\n<option".
	(($data[2] eq 'en') ? ' selected' : '') ." value='en'>End-use netblock</option>\n<option".
	(($data[2] eq 'in') ? ' selected' : '') ." value='in'>Internal netblock</option>\n".
	"</select>\n";
      $html =~ s/\$\$TYPESELECT\$\$/$blockoptions/g;
    } else {
      $html =~ s/\$\$TYPESELECT\$\$/$disp_alloctypes{$data[2]}<input type=hidden name=alloctype value="$data[2]">/g;
    }
    $html =~ s/\$\$CITY\$\$/<input type=text name=city value="$data[3]">/g;
    $html =~ s/\$\$CIRCID\$\$/<input type="text" name="circid" value="$data[4]" maxlength=64 size=64 class="regular">/g;
    $html =~ s/\$\$DESC\$\$/<input type="text" name="desc" value="$data[5]" maxlength=64 size=64 class="regular">/g;
    $html =~ s|\$\$NOTES\$\$|<textarea rows="8" cols="64" name="notes" class="regular">$data[6]</textarea>|g;
  } else {
    $html =~ s/\$\$CUSTID\$\$/$data[1]/g;
    $html =~ s/\$\$TYPESELECT\$\$/$disp_alloctypes{$data[2]}/g;
    $html =~ s/\$\$CITY\$\$/$data[3]/g;
    $html =~ s/\$\$CIRCID\$\$/$data[4]/g;
    $html =~ s/\$\$DESC\$\$/$data[5]/g;
    $html =~ s/\$\$NOTES\$\$/$data[6]/g;
  }
  my ($lastmod,undef) = split /\s+/, $data[7];
  $html =~ s/\$\$LASTMOD\$\$/$lastmod/g;

  # Allows us to "correctly" colour backgrounds in table
  my $i=1;

  # More ACL trickery - we can live with forms that don't submit,
  # but we can't leave the extra table rows there, and we *really*
  # can't leave the submit buttons there.
  my $updok = '';
  if ($IPDBacl{$authuser} =~ /c/) {
    $updok = qq(<tr class="color$i"><td colspan=2><div class="center">).
	qq(<input type="submit" value=" Update this block " class="regular">).
	"</div></td></tr></form>\n";
    $i++;
  }
  $html =~ s/\$\$UPDOK\$\$/$updok/g;

  my $delok = '';
  if ($IPDBacl{$authuser} =~ /d/) {
    $delok = qq(<form method="POST" action="main.cgi">
	<tr class="color$i"><td colspan=2 class="regular"><div class=center>
	<input type="hidden" name="action" value="delete">
	<input type="hidden" name="block" value="$webvar{block}">
	<input type="hidden" name="alloctype" value="$data[2]">
	<input type=submit value=" Delete this block ">
	</div></td></tr>);
  }
  $html =~ s/\$\$DELOK\$\$/$delok/;

  print $html;

} # edit()


# Stuff new info about a block into the db
# action=update
sub update {

  # Make sure incoming data is in correct format - custID among other things.
  return if !validateInput;

  # SQL transaction wrapper
  eval {
    # Relatively simple SQL transaction here.
    my $sql;
    if (my $pooltype = ($webvar{alloctype} =~ /^(.)i$/) ) {
      $sql = "update poolips set custid='$webvar{custid}',notes='$webvar{notes}',".
	"circuitid='$webvar{circid}',description='$webvar{desc}',city='$webvar{city}' ".
	"where ip='$webvar{block}'";
    } else {
      $sql = "update allocations set custid='$webvar{custid}',".
	"description='$webvar{desc}',notes='$webvar{notes}',city='$webvar{city}',".
	"type='$webvar{alloctype}',circuitid='$webvar{circid}' where cidr='$webvar{block}'";
    }
    # Log the details of the change.
    syslog "debug", $sql;
    $sth = $ip_dbh->prepare($sql);
    $sth->execute;
    $ip_dbh->commit;
  };
  if ($@) {
    my $msg = $@;
    carp "Transaction aborted because $msg";
    eval { $ip_dbh->rollback; };
    syslog "err", "$authuser could not update block/IP '$webvar{block}': '$msg'";
    printError("Could not update block/IP $webvar{block}: $msg");
    return;
  }

  # If we get here, the operation succeeded.
  syslog "notice", "$authuser updated $webvar{block}";
  open (HTML, "../updated.html")
	or croak "Could not open updated.html :$!";
  my $html = join('', <HTML>);

  $html =~ s/\$\$BLOCK\$\$/$webvar{block}/g;
  $webvar{city} = desanitize($webvar{city});
  $html =~ s/\$\$CITY\$\$/$webvar{city}/g;
  $html =~ s/\$\$ALLOCTYPE\$\$/$webvar{alloctype}/g;
  $html =~ s/\$\$TYPEFULL\$\$/$disp_alloctypes{$webvar{alloctype}}/g;
  $html =~ s/\$\$CUSTID\$\$/$webvar{custid}/g;
  $webvar{circid} = desanitize($webvar{circid});
  $html =~ s/\$\$CIRCID\$\$/$webvar{circid}/g;
  $webvar{desc} = desanitize($webvar{desc});
  $html =~ s/\$\$DESC\$\$/$webvar{desc}/g;
  $webvar{notes} = desanitize($webvar{notes});
  $html =~ s/\$\$NOTES\$\$/$webvar{notes}/g;

  print $html;

} # update()


# Delete an allocation.
sub remove {
  if ($IPDBacl{$authuser} !~ /d/) {
    printError("You shouldn't have been able to get here.  Access denied.");
    return;
  }

  #show confirm screen.
  open HTML, "../confirmRemove.html"
	or croak "Could not open confirmRemove.html :$!";
  my $html = join('', <HTML>);
  close HTML;

  # Serves'em right for getting here...
  if (!defined($webvar{block})) {
    printError("Error 332");
    return;
  }

  my ($cidr, $custid, $type, $city, $circid, $desc, $notes, $alloctype);

  if ($webvar{alloctype} eq 'rm') {
    $sth = $ip_dbh->prepare("select cidr,city from routed where cidr='$webvar{block}'");
    $sth->execute();

# This feels...  extreme.
    croak $sth->errstr() if($sth->errstr());

    $sth->bind_columns(\$cidr,\$city);
    $sth->execute();
    $sth->fetch || croak $sth->errstr();
    $custid = "N/A";
    $alloctype = $webvar{alloctype};
    $circid = "N/A";
    $desc = "N/A";
    $notes = "N/A";

  } elsif ($webvar{alloctype} eq 'mm') {
    $cidr = $webvar{block};
    $city = "N/A";
    $custid = "N/A";
    $alloctype = $webvar{alloctype};
    $circid = "N/A";
    $desc = "N/A";
    $notes = "N/A";
  } elsif ($webvar{alloctype} =~ /^.i$/) { # done with alloctype=[rm]m

    # Unassigning a static IP
    my $sth = $ip_dbh->prepare("select ip,custid,city,type,notes,circuitid from poolips".
	" where ip='$webvar{block}'");
    $sth->execute();
#  croak $sth->errstr() if($sth->errstr());

    $sth->bind_columns(\$cidr, \$custid, \$city, \$alloctype, \$notes, \$circid);
    $sth->fetch() || croak $sth->errstr;

  } else { # done with alloctype=~ /^.i$/

    my $sth = $ip_dbh->prepare("select cidr,custid,type,city,circuitid,description,notes from ".
	"allocations where cidr='$webvar{block}'");
    $sth->execute();
#	croak $sth->errstr() if($sth->errstr());

    $sth->bind_columns(\$cidr, \$custid, \$alloctype, \$city, \$circid, \$desc, \$notes);
    $sth->fetch() || carp $sth->errstr;
  } # end cases for different alloctypes

  # Munge everything into HTML
  $html =~ s|Please confirm|Please confirm <b>removal</b> of|;
  $html =~ s|\$\$BLOCK\$\$|$cidr|g;
  $html =~ s|\$\$TYPEFULL\$\$|$disp_alloctypes{$alloctype}|g;
  $html =~ s|\$\$ALLOCTYPE\$\$|$alloctype|g;
  $html =~ s|\$\$CITY\$\$|$city|g;
  $html =~ s|\$\$CUSTID\$\$|$custid|g;
  $html =~ s|\$\$CIRCID\$\$|$circid|g;
  $html =~ s|\$\$DESC\$\$|$desc|g;
  $html =~ s|\$\$NOTES\$\$|$notes|g;

  $html =~ s|\$\$ACTION\$\$|finaldelete|g;

  # Set the warning text.
  if ($alloctype =~ /^.[pd]$/) {
    $html =~ s|<!--warn-->|<tr bgcolor="black"><td colspan="2"><div class="red">Warning: clicking confirm will remove this record entirely.<br>Any IPs allocated from this pool will also be removed!</div></td></tr>|;
  } else {
    $html =~ s|<!--warn-->|<tr bgcolor="black"><td colspan="2"><div class="red">Warning: clicking confirm will remove this record entirely.</div></td></tr>|;
  }

  print $html;
} # end edit()


# Delete an allocation.  Return it to the freeblocks table;  munge
# data as necessary to keep as few records as possible in freeblocks
# to prevent weirdness when allocating blocks later.
# Remove IPs from pool listing if necessary
sub finalDelete {
  if ($IPDBacl{$authuser} !~ /d/) {
    printError("You shouldn't have been able to get here.  Access denied.");
    return;
  }

  my ($code,$msg) = deleteBlock($ip_dbh, $webvar{block}, $webvar{alloctype});

  if ($code eq 'OK') {
    print "<div class=heading align=center>Success!  $webvar{block} deallocated.</div>\n";
    syslog "notice", "$authuser deallocated '$webvar{alloctype}'-type netblock $webvar{block}";
    # Notify tech@ when a block/IP is deallocated
#    mailNotify('tech@example.com',"REMOVED: $disp_alloctypes{$webvar{alloctype}} $webvar{block}",
#	"$disp_alloctypes{$webvar{alloctype}} $webvar{block} deallocated by $authuser\n");
  } else {
    if ($webvar{alloctype} =~ /^.i$/) {
      syslog "err", "$authuser could not deallocate static IP '$webvar{block}': '$msg'";
      printError("Could not deallocate static IP $webvar{block}: $msg");
    } else {
      syslog "err", "$authuser could not deallocate netblock '$webvar{block}': '$msg'";
      printError("Could not deallocate netblock $webvar{block}: $msg");
    }
  }

} # finalDelete


sub exitError {
  my $errStr = $_[0];
  printHeader('','');
  print qq(<center><p class="regular"> $errStr </p>
<input type="button" value="Back" onclick="history.go(-1)">
</center>
);
  printFooter();
  exit;
} # errorExit


# Just in case we manage to get here.
exit 0;
