#!/usr/bin/perl
# ipdb/cgi-bin/main.cgi
###
# SVN revision info
# $Date: 2015-08-26 20:10:01 +0000 (Wed, 26 Aug 2015) $
# SVN revision $Rev: 771 $
# Last update by $Author: kdeugau $
###
# Copyright (C) 2004-2010 - Kris Deugau

use strict;		
use warnings;	
use CGI::Carp qw(fatalsToBrowser);
use CGI::Simple;
use HTML::Template;
use DBI;
use POSIX qw(ceil);
use NetAddr::IP;
use Frontier::Client;

use Sys::Syslog;

# don't remove!  required for GNU/FHS-ish install from tarball
##uselib##

use CustIDCK;
use MyIPDB;

openlog "IPDB","pid","$IPDB::syslog_facility";

## Environment.  Collect some things, process some things, set some things...

# 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'};
}

# anyone got a better name?  :P
my $thingroot = $ENV{SCRIPT_FILENAME};
$thingroot =~ s|cgi-bin/main.cgi||;

syslog "debug", "$authuser active, $ENV{'REMOTE_ADDR'}";

##fixme there *must* be a better order to do things in so this can go back where it was
# CGI fiddling done here so we can declare %webvar so we can alter $webvar{action}
# to show the right page on DB errors.
# Set up the CGI object...
my $q = new CGI::Simple;
# ... and get query-string params as well as POST params if necessary
$q->parse_query_string;

# Convenience;  saves changing all references to %webvar
##fixme:  tweak for handling <select multiple='y' size=3> (list with multiple selection)
my %webvar = $q->Vars;

# 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 $errstr;
($ip_dbh,$errstr) = connectDB_My;
if (!$ip_dbh) {
  $webvar{action} = "dberr";
} else {
  initIPDBGlobals($ip_dbh);
}

# Set up some globals
$ENV{HTML_TEMPLATE_ROOT} = $thingroot."templates";

my $header = HTML::Template->new(filename => "header.tmpl");
my $footer = HTML::Template->new(filename => "footer.tmpl");
my $utilbar = HTML::Template->new(filename => "utilbar.tmpl", loop_context_vars => 1, global_vars => 1);

print "Content-type: text/html\n\n";

$header->param(version => $IPDB::VERSION);
$header->param(addperm => $IPDBacl{$authuser} =~ /a/);
$header->param(webpath => $IPDB::webpath);

$utilbar->param(webpath => $IPDB::webpath);

print $header->output;

##fixme:  whine and complain when the user is not present in the ACL hash above

#main()
my $aclerr;

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

my $page;
if (-e "$ENV{HTML_TEMPLATE_ROOT}/$webvar{action}.tmpl") {
  $page = HTML::Template->new(filename => "$webvar{action}.tmpl", loop_context_vars => 1, global_vars => 1);
} else {
  $page = HTML::Template->new(filename => "dunno.tmpl");
}

if($webvar{action} eq 'index') {
  showSummary();
} elsif ($webvar{action} eq 'addmaster') {
  if ($IPDBacl{$authuser} !~ /a/) {
    $aclerr = 'addmaster';
  }

  # Retrieve the list of DNS locations if we've got a place to grab them from
  if ($IPDB::rpc_url) {
    my %rpcargs = (
	rpcuser => $authuser,
	group => 1,	# bleh
	defloc => '',
	);
    my $result = IPDB::_rpc('getLocDropdown', %rpcargs);
    $page->param(loclist => $result);
  }

} elsif ($webvar{action} eq 'newmaster') {

  if ($IPDBacl{$authuser} !~ /a/) {
    $aclerr = 'addmaster';
  } else {
    my $cidr = new NetAddr::IP $webvar{cidr};
    $page->param(cidr => "$cidr");

    my ($code,$msg) = addMaster($ip_dbh, $webvar{cidr}, (vrf => $webvar{vrf}, rdns => $webvar{rdns}, 
	rwhois => $webvar{rwhois}, defloc => $webvar{loc}, user => $authuser) );

    if ($code eq 'FAIL') {
      syslog "err", "Could not add master block '$webvar{cidr}' to database: '$msg'";
      $page->param(err => $msg);
    } else {
      $page->param(parent => $msg);
      if ($code eq 'WARN') {
        $IPDB::errstr =~ s/\n\n/<br>\n/g;
        $IPDB::errstr =~ s/:\n/:<br>\n/g;
        $page->param(warn => $IPDB::errstr);
      }
      syslog "info", "$authuser added master block $webvar{cidr}";
    }

  } # ACL check

} # end add new master

elsif ($webvar{action} eq 'showsubs') {
  showSubs();
}

elsif($webvar{action} eq 'listpool') {
  showPool();
}

# 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 'split') {
  prepSplit();
}
elsif($webvar{action} eq 'dosplit') {
  doSplit();
}
elsif($webvar{action} eq 'merge') {
  prepMerge();
}
elsif($webvar{action} eq 'confmerge') {
  confMerge();
}
elsif($webvar{action} eq 'domerge') {
  doMerge();
}
elsif($webvar{action} eq 'delete') {
  remove();
}
elsif($webvar{action} eq 'finaldelete') {
  finalDelete();
}
elsif ($webvar{action} eq 'nodesearch') {
  my $nodelist = getNodeList($ip_dbh);
  $page->param(nodelist => $nodelist);
}

# DB failure.  Can't do much here, really.
elsif ($webvar{action} eq 'dberr') {
  $page->param(errmsg => $errstr);
}

# Default is an error.  It shouldn't be possible to get here unless you're
# randomly feeding in values for webvar{action}.
else {
  my $rnd = rand 500;
  my $boing = sprintf("%.2f", rand 500);
  my @excuses = (
	"Aether cloudy.  Ask again later about $webvar{action}.",
	"The gods are unhappy with your sacrificial $webvar{action}.",
	"Because one of $webvar{action}'s legs are both the same",
	"<b>wibble</b><br>Can't $webvar{action}, the grue will get me!<br>Can't $webvar{action}, the grue will get me!",
	"Hey, man, you've had your free $webvar{action}.  Next one's gonna...  <i>cost</i>....",
	"I ain't done $webvar{action}",
	"Oooo, look!  A flying $webvar{action}!",
	"$webvar{action} too evil, avoiding.",
	"Rocks fall, $webvar{action} dies.",
	"Bit bucket must be emptied before I can $webvar{action}..."
	);
  $page->param(dunno => $excuses[$rnd/50.0]);
}
## Finally! Done with that NASTY "case" emulation!


# Switch to a different template if we've tripped on an ACL error.
# Note that this should only be exercised in development, when
# deeplinked, or when being attacked;  normal ACL handling should
# remove the links a user is not allowed to click on.
if ($aclerr) {
  $page = HTML::Template->new(filename => "aclerror.tmpl");
  $page->param(ipdbfunc => $aclmsg{$aclerr});
}

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

## Do all our printing here so we can generate errors and stick them into the slots in the templates.

# can't do this yet, too many blowups
#print "Content-type: text/html\n\n", $header->output;
$page->param(webpath => $IPDB::webpath);
print $utilbar->output;
print $page->output;

# include the admin tools link in the output?
$footer->param(adminlink => ($IPDBacl{$authuser} =~ /A/));
$footer->param(webpath => $IPDB::webpath);
print $footer->output;

# Just in case something waaaayyy down isn't in place
# properly... we exit explicitly.
exit 0;


# Initial display:  Show master blocks with total allocated subnets, total free subnets
sub showSummary {
  my $masterlist = listSummary($ip_dbh);
  $page->param(masterlist => $masterlist);

  $page->param(addmaster => ($IPDBacl{$authuser} =~ /a/) );
} # showSummary


# Display blocks immediately within a given parent
sub showSubs {
  # Which layout?
  if ($IPDB::sublistlayout == 2) {

    # 2-part layout;  mixed containers and end-use allocations and free blocks.
    # Containers have a second line for the subblock metadata.
    # We need to load an alternate template for this case.
    $page = HTML::Template->new(filename => "showsubs2.tmpl", loop_context_vars => 1, global_vars => 1);

    $page->param(maydel => ($IPDBacl{$authuser} =~ /d/));

    my $sublist = listSubs($ip_dbh, parent => $webvar{parent});
    $page->param(sublist => $sublist);

  } else {

    # 3-part layout;  containers, end-use allocations, and free blocks

    my $contlist = listContainers($ip_dbh, parent => $webvar{parent});
    $page->param(contlist => $contlist);

    my $alloclist = listAllocations($ip_dbh, parent => $webvar{parent});
    $page->param(alloclist => $alloclist);

    # only show "delete" button if we have no container or usage allocations
    $page->param(maydel => ($IPDBacl{$authuser} =~ /d/) && !(@$contlist || @$alloclist));

  }

  # Common elements
  my $pinfo = getBlockData($ip_dbh, $webvar{parent});

##fixme:  do we add a wrapper to not show the edit link for master blocks?
#$page->param(editme => 1) unless $pinfo->{type} ne 'mm';

  my $crumbs = getBreadCrumbs($ip_dbh, $pinfo->{parent_id});
  my @rcrumbs = reverse (@$crumbs);
  $utilbar->param(breadcrumb => \@rcrumbs);

  $page->param(self_id => $webvar{parent});
  $page->param(block => $pinfo->{block});
  $page->param(mayadd => ($IPDBacl{$authuser} =~ /a/));

  my $flist = listFree($ip_dbh, parent => $webvar{parent});
  $page->param(freelist => $flist);
} # showSubs


# List the IPs used in a pool
sub showPool {

  my $poolinfo = getBlockData($ip_dbh, $webvar{pool});
  my $cidr = new NetAddr::IP $poolinfo->{block};
  $page->param(vlan => $poolinfo->{vlan});

  # Tree navigation
  my $crumbs = getBreadCrumbs($ip_dbh, $poolinfo->{parent_id});
  my @rcrumbs = reverse (@$crumbs);
  $utilbar->param(breadcrumb => \@rcrumbs);

  $page->param(block => $cidr);
  $page->param(netip => $cidr->addr);
  $cidr++;
  $page->param(gate => $cidr->addr);
  $cidr--;  $cidr--;
  $page->param(bcast => $cidr->addr);
  $page->param(mask => $cidr->mask);

  $page->param(disptype => $disp_alloctypes{$poolinfo->{type}});
  $page->param(city => $poolinfo->{city});

  # Only display net/gw/bcast if it's a "real" netblock and not a PPP(oE) lunacy
  $page->param(realblock => $poolinfo->{type} =~ /^.d$/);

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

  my $plist = listPool($ip_dbh, $webvar{pool});
  # technically slightly more efficient to check the ACL in an if () once outside the foreach
  foreach (@{$plist}) {
    $$_{maydel} = $IPDBacl{$authuser} =~ /d/;
  }
  $page->param(poolips => $plist);
} # end showPool


# 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/) {
    $aclerr = 'addblock';
    return;
  }

  # hack pthbttt eww
  $webvar{parent} = 0 if !$webvar{parent};
  $webvar{block} = '' if !$webvar{block};

  $page->param(allocfrom => $webvar{block});	# fb-assign flag, if block is set, we're in fb-assign

  if ($webvar{fbid} || $webvar{fbtype}) {

    # Common case, according to reported usage.  Block to assign is specified.
    my $block = new NetAddr::IP $webvar{block};

    my ($rdns,$cached) = getBlockRDNS($ip_dbh, id => $webvar{parent}, type => $webvar{fbtype}, user => $authuser);
    $page->param(rdns => $rdns) if $rdns;
    $page->param(parent => $webvar{parent});
    $page->param(fbid => $webvar{fbid});
    # visual flag that we're working IPDB-local, not off more authoritative data in dnsadmin
    $page->param(cached => $cached);

    my $pinfo = getBlockData($ip_dbh, $webvar{parent});
    # seems reasonable that a new allocation would share a VRF with its parent
    $page->param(pvrf => $pinfo->{vrf});

    # Tree navigation
    my $crumbs = getBreadCrumbs($ip_dbh, $webvar{parent});
    my @rcrumbs = reverse (@$crumbs);
    $utilbar->param(breadcrumb => \@rcrumbs);

    $webvar{fbtype} = '' if !$webvar{fbtype};
    if ($webvar{fbtype} eq 'i') {
      my $ipinfo = getBlockData($ip_dbh, $webvar{block}, 'i');
      $page->param(
	fbip => 1,
	block => $ipinfo->{block},
	fbdisptype => $list_alloctypes{$ipinfo->{type}},
	type => $ipinfo->{type},
	allocfrom => $pinfo->{block},
	);
    } else {
      # get "primary" alloctypes, since these are all that can correctly be assigned if we're in this branch
      my $tlist = getTypeList($ip_dbh, 'n');
      $tlist->[0]->{sel} = 1;
      $page->param(typelist => $tlist, block => $block);
    }

  } else {

    # Uncommon case, according to reported usage.  Block to assign needs to be found based on criteria.
    my $mlist = getMasterList($ip_dbh, 'c');
    $page->param(masterlist => $mlist);

    my @pops;
    foreach my $pop (@citylist) {
      my %row = (pop => $pop);
      push (@pops, \%row);
    }
    $page->param(pops => \@pops);

    # get all standard alloctypes
    my $tlist = getTypeList($ip_dbh, 'a');
    $tlist->[0]->{sel} = 1;
    $page->param(typelist => $tlist);
  }

  my @cities;
  foreach my $city (@citylist) {
    my %row = (city => $city);
    push (@cities, \%row);
  }
  $page->param(citylist => \@cities);

## node hack
  my $nlist = getNodeList($ip_dbh);
  $page->param(nodelist => $nlist);
## end node hack

  $page->param(privdata => $IPDBacl{$authuser} =~ /s/);

} # assignBlock


# Take info on requested IP assignment and see what we can provide.
sub confirmAssign {
  if ($IPDBacl{$authuser} !~ /a/) {
    $aclerr = 'addblock';
    return;
  }

  my $cidr;
  my $resv;   # Reserved for expansion.
  my $alloc_from;
  my $fbid = $webvar{fbid};
  my $p_id = $webvar{parent};

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

  # make sure this is defined
  $webvar{fbassign} = 'n' if !$webvar{fbassign};

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

  if ($webvar{alloctype} =~ /^.i$/ && $webvar{fbassign} ne 'y') {
    if (!$webvar{pop}) {
      $page->param(err => "Please select a location/POP site to allocate from.");
      return;
    }
    my $plist = getPoolSelect($ip_dbh, $webvar{alloctype}, $webvar{pop});
    $page->param(staticip => 1);
    $page->param(poollist => $plist) if $plist;
    $cidr = "Single static IP";
##fixme:  need to handle "no available pools"

  } else { # end show pool options

    if ($webvar{fbassign} && $webvar{fbassign} eq 'y') {

      # Tree navigation
      my $crumbs = getBreadCrumbs($ip_dbh, $webvar{parent});
      my @rcrumbs = reverse (@$crumbs);
      $utilbar->param(breadcrumb => \@rcrumbs);

      $cidr = new NetAddr::IP $webvar{block};
      $alloc_from = new NetAddr::IP $webvar{allocfrom};
      $webvar{maskbits} = $cidr->masklen;
      # Some additional checks are needed for reserving free space
      if ($webvar{reserve}) {
        if ($cidr == $alloc_from) {
# We could still squirm and fiddle to try to find a way to reserve space, but the storage model for
# IPDB means that all continguous free space is kept in the smallest number of strict CIDR netblocks
# possible.  (In theory.)  If the request and the freeblock are the same, it is theoretically impossible
# to reserve an equivalent-sized block either ahead or behind the requested one, because the pair
# together would never be a strict CIDR block.
          $page->param(warning => "Can't reserve space for expansion;  free block and requested allocation are the same.");
          delete $webvar{reserve};
        } else {
          # Find which new free block will match the reqested block.
          # Take the requested mask, shift by one
          my $tmpmask = $webvar{maskbits};
          $tmpmask--;
          # find the subnets with that mask in the selected free block
          my @pieces = $alloc_from->split($tmpmask);
          foreach my $slice (@pieces) {
            if ($slice->contains($cidr)) {
              # For the subnet that contains the requested block, split that in two,
              # and flag/cache the one that's not the requested block.
              my @bits = $slice->split($webvar{maskbits});
              if ($bits[0] == $cidr) {
                $resv = $bits[1];
              } else {
                $resv = $bits[0];
              }
            }
          }
        }
      } # reserve block check

    } else { # done with direct freeblocks assignment

      if (!$webvar{maskbits}) {
        $page->param(err => "Please specify a CIDR mask length.");
	return;
      }

##fixme ick, ew, bleh.  gotta handle the failure message generation better.  push it into findAllocateFrom()?
      my $failmsg = "No suitable free block found.<br>\n";
      if ($webvar{alloctype} eq 'rm') {
	$failmsg .= "We do not have a free routeable block of that size.<br>\n".
		"You will have to either route a set of smaller netblocks or a single smaller netblock.";
      } else {
	if ($webvar{alloctype} =~ /^.[pc]$/) {
	  $failmsg .= "You will have to route another superblock from one of the<br>\n".
		"master blocks or chose a smaller block size for the pool.";
	} else {
	  if (!$webvar{pop}) {
	    $page->param(err => 'Please select a POP to route the block from/through.');
	    return;
	  }
	  $failmsg .= "You will have to route another superblock to $webvar{pop}<br>\n".
		"from one of the master blocks";
          if ($webvar{reserve}) {
            $failmsg .= ', choose a smaller blocksize, or uncheck "Reserve space for expansion".';
          } else {
            $failmsg .= " or chose a smaller blocksize.";
          }
	}
      }

      # if requesting extra space "reserved for expansion", we need to find a free
      # block at least double the size of the request.
      if ($webvar{reserve}) {
        $webvar{maskbits}--;
      }

      ($fbid,$cidr,$p_id) = findAllocateFrom($ip_dbh, $webvar{maskbits}, $webvar{alloctype},
	$webvar{city}, $webvar{pop}, (master => $webvar{allocfrom}, allowpriv => $webvar{allowpriv}) );
      if (!$cidr) {
	$page->param(err => $failmsg);
	return;
      }
      $cidr = new NetAddr::IP $cidr;

      $alloc_from = "$cidr";

      # when autofinding a block to allocate from, use the first piece of the found
      # block for the allocation, and the next piece for the "reserved for expansion".
      if ($webvar{reserve}) {
        # reset the mask to the real requested one, now that we've got a
        # block large enough for the request plus reserve
        $webvar{maskbits}++;
        ($cidr,$resv) = $cidr->split($webvar{maskbits});
      }

      # 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];
      }
    } # check for freeblocks assignment or IPDB-controlled assignment

    # Generate the IP list for the new allocation in case someone wants to set per-IP rDNS right away.
    # We don't do this on the previous page because we don't know how big a block or even what IP range
    # it's for (if following the "normal" allocation process)
    if ($IPDBacl{$authuser} =~ /c/
	&& $cidr->masklen != $cidr->bits
	&& ($cidr->bits - $cidr->masklen) <= $IPDB::maxrevlist
	&& $webvar{alloctype} !~ /^.[dpi]/
	# do we want to allow v6 at all?
	#&& ! $cidr->{isv6}
	) {
      my @list;
      foreach my $ip (@{$cidr->splitref()}) {
        my %row;
        $row{r_ip} = $ip->addr;
        $row{iphost} = '';
        push @list, \%row;
      }
      $page->param(r_iplist => \@list);
      # We don't use this here, because these IPs should already be bare.
      # ... or should we be paranoid?  Make it a config option?
      #getRDNSbyIP($ip_dbh, type => $webvar{alloctype}, range => "$cidr", user => $authuser) );
    }
  } # if ($webvar{alloctype} =~ /^.i$/)

## node hack
  if ($webvar{node} && $webvar{node} ne '-') {
    my $nodename = getNodeName($ip_dbh, $webvar{node});
    $page->param(nodename => $nodename);
    $page->param(nodeid => $webvar{node});
  }
## end node hack

  # flag DNS info if we can't publish the entry remotely
  my $pinfo = getBlockData($ip_dbh, $webvar{parent});
  $page->param(dnslocal => 1) unless ($pinfo->{revpartial} || $pinfo->{revavail});

  # reserve for expansion
  $page->param(reserve => $webvar{reserve});
  # probably just preventing a little log noise doing this;  could just set the param
  # all the time since it won't be shown if the reserve param above isn't set.
#  if ($webvar{reserve}) {
    $page->param(resvblock => $resv);
#  }

  # Stick in the allocation data
  $page->param(alloc_type => $webvar{alloctype});
  $page->param(typefull => $q->escapeHTML($disp_alloctypes{$webvar{alloctype}}));
  $page->param(alloc_from => $alloc_from);
  $page->param(parent => $p_id);
  $page->param(fbid => $fbid);
  $page->param(cidr => $cidr);
  $page->param(rdns => $webvar{rdns});
  $page->param(vrf => $webvar{vrf});
  $page->param(vlan => $webvar{vlan});
  $page->param(city => $q->escapeHTML($webvar{city}));
  $page->param(custid => $webvar{custid});
  $page->param(circid => $q->escapeHTML($webvar{circid}));
  $page->param(desc => $q->escapeHTML($webvar{desc}));

##fixme: find a way to have the displayed copy have <br> substitutions
# for newlines, and the <input> value have either encoded or bare newlines.
# Also applies to privdata.
  $page->param(notes => $q->escapeHTML($webvar{notes},'y'));

  # Check to see if user is allowed to do anything with sensitive data
  my $privdata = '';
  $page->param(privdata => $q->escapeHTML($webvar{privdata},'y'))
	if $IPDBacl{$authuser} =~ /s/;

  # Yay!  This now has it's very own little home.
  $page->param(billinguser => $webvar{userid})
	if $webvar{userid};

##fixme:  this is only needed iff confirm.tmpl and
# confirmRemove.tmpl are merged (quite possible, just
# a little tedious)
  $page->param(action => "insert");

} # end confirmAssign


# Do the work of actually inserting a block in the database.
sub insertAssign {
  if ($IPDBacl{$authuser} !~ /a/) {
    $aclerr = 'addblock';
    return;
  }
  # Some things are done more than once.
  return if !validateInput();

  if (!defined($webvar{privdata})) {
    $webvar{privdata} = '';
  }

  # $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.

##fixme:  consider just passing \%webvar to allocateBlock()?
  # collect per-IP rDNS fields.  only copy over the ones that actually have something in them.
  my %iprev;
  foreach (keys %webvar) {
    $iprev{$_} = $webvar{$_} if /host_[\d.a-fA-F:]+/ && $webvar{$_};
  }

  # Easier to see and cosmetically fiddle the list like this
  my %insert_args = (
	cidr		=> $webvar{fullcidr},
	fbid		=> $webvar{fbid},
	reserve		=> $webvar{reserve},
	parent		=> $webvar{parent},
	custid		=> $webvar{custid},
	type		=> $webvar{alloctype},
	city		=> $webvar{city}, 
	desc		=> $webvar{desc},
	notes		=> $webvar{notes},
	circid		=> $webvar{circid},
	privdata	=> $webvar{privdata},
	nodeid		=> $webvar{node},
	rdns		=> $webvar{rdns},
	vrf		=> $webvar{vrf},
	vlan		=> $webvar{vlan},
	user		=> $authuser,
	);

  my $pinfo = getBlockData($ip_dbh, $webvar{parent});

  # clean up a minor mess with guided allocation of static IPs
  if ($webvar{alloctype} =~ /^.i$/) {
    $insert_args{alloc_from} = $pinfo->{block};
  }

  my ($code,$msg) = allocateBlock($ip_dbh, %insert_args, iprev => \%iprev);

  if ($code eq 'OK') {
    # breadcrumbs lite!  provide at least a link to the parent of the block we just allocated.
    $page->param(parentid => $webvar{parent});
    $page->param(parentblock => $pinfo->{block});

    if ($webvar{alloctype} =~ /^.i$/) {
      $msg =~ s|/32||;
      $page->param(staticip => $msg);
      $page->param(custid => $webvar{custid});
      $page->param(billinguser => $webvar{billinguser});
      mailNotify($ip_dbh, "a$webvar{alloctype}", "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 {
      my $netblock = new NetAddr::IP $webvar{fullcidr};
      $page->param(fullcidr => $webvar{fullcidr});
      $page->param(alloctype => $disp_alloctypes{$webvar{alloctype}});
      $page->param(custid => $webvar{custid});

      # Full breadcrumbs
      my $crumbs = getBreadCrumbs($ip_dbh, $webvar{parent});
      my @rcrumbs = reverse (@$crumbs);
      $utilbar->param(breadcrumb => \@rcrumbs);

      if ($webvar{alloctype} eq 'pr' && $webvar{billinguser}) {
	$page->param(billinguser => $webvar{billinguser});
	$page->param(custid => $webvar{custid});
	$page->param(netaddr => $netblock->addr);
	$page->param(masklen => $netblock->masklen);
      }
      mailNotify($ip_dbh, "a$webvar{alloctype}", "ADDED: $disp_alloctypes{$webvar{alloctype}} allocation",
	"$disp_alloctypes{$webvar{alloctype}} $webvar{fullcidr} allocated to customer $webvar{custid}\n".
	"Description: $webvar{desc}\n\nAllocated by: $authuser\n");
    }
    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'";
    $page->param(err => "Allocation of $webvar{fullcidr} as '$disp_alloctypes{$webvar{alloctype}}' failed:");
    $page->param(errmsg => $msg);
  }

} # 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 '-') {
    $page->param(err => '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.
    $page->param(err => '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}) {
      $page->param(err => 'Please enter a customer ID.');
      return;
    }
    # Crosscheck with billing.
    my $status = CustIDCK->custid_exist($webvar{custid});
    if ($CustIDCK::Error) {
      $page->param(err => "Error verifying customer ID: ".$CustIDCK::ErrMsg);
      return;
    }
    if (!$status) {
      $page->param(err => "Customer ID not valid.  Make sure the Customer ID ".
	"is correct.<br>\nUse STAFF for staff static IPs, and $IPDB::defcustid for any other ".
	"non-customer assignments.");
      return;
    }
#    print "<!-- [ In validateInput().  Insert customer ID cross-check here. ] -->\n";
  } else {
    # New!  Improved!  And now Loaded From The Database!!
    if ((!$webvar{custid}) || ($webvar{custid} ne 'STAFF')) {
      $webvar{custid} = $def_custids{$webvar{alloctype}};
    }
  }

## hmmm....  is this even useful?
if (0) {
  # 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';
##fixme:  hook to force-set POP or city on certain alloctypes
# if ($webvar{alloctype =~ /foo,bar,bz/ { $webvar{pop} = 'blah'; }
    if ($webvar{pop} && $webvar{pop} =~ /^-$/) {
      $flag = 'to route the block from/through';
    }
  }

  # if the alloctype has a restricted city/POP list as determined above,
  # and the reqested city/POP does not match that list, complain
  if ($flag ne 'n') {
    $page->param(err => "Please choose a valid POP location $flag.  Valid ".
	"POP locations are currently:<br>\n".join (" - ", @poplist));
    return;
  }
}

  # VRF.  Not a full validity check, just a basic sanity check.
  if ($webvar{vrf}) {
    # Trim leading and trailing whitespace first
    $webvar{vrf} =~ s/^\s+//;
    $webvar{vrf} =~ s/\s+$//;
    if ($webvar{vrf} !~ /^[\w\d_.-]{1,32}$/) {
      $page->param(err => "VRF values may only contain alphanumerics, and may not be more than 32 characters");
      return;
    }
  }

  # VLAN.  Should we allow/use VLAN names, or just the numeric ID?
  if ($webvar{vlan}) {
    # Trim leading and trailing whitespace first
    $webvar{vlan} =~ s/^\s+//;
    $webvar{vlan} =~ s/\s+$//;
    # ...  ve make it ze configurable thingy!
    if ($IPDB::numeric_vlan) {
      if ($webvar{vlan} !~ /^\d+$/) {
        $page->param(err => "VLANs must be numeric");
        return;
      }
    } else {
      if ($webvar{vlan} !~ /^[\w\d_.-]+$/) {
        $page->param(err => "VLANs must be alphanumeric");
        return;
      }
    }
  }

  return 'OK';
} # end validateInput


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

  # snag block info from db
  my $blockinfo = getBlockData($ip_dbh, $webvar{id}, $webvar{basetype});
  my $cidr = new NetAddr::IP $blockinfo->{block};
  $page->param(id       => $webvar{id});
  $page->param(basetype => $webvar{basetype});

  # Tree navigation
  my $crumbs = getBreadCrumbs($ip_dbh, $blockinfo->{parent_id});
  my @rcrumbs = reverse (@$crumbs);
  $utilbar->param(breadcrumb => \@rcrumbs);

  # Show link to IP list for pools
  $page->param(ispool => 1) if $blockinfo->{type} =~ /^.[dp]$/;

  # Clean up extra whitespace on alloc type.  Mainly a legacy-data cleanup.
  $blockinfo->{type} =~ s/\s//;

##fixme:  The case of "allocation larger than a /24" (or any similar case
# where the allocation is larger than the zone(s) in DNS) doesn't work well.
# Best solution may just be to add a warning that the entry shown may not be
# correct/complete.
  if ($blockinfo->{revavail} || $blockinfo->{revpartial}) {
    $page->param(showrev => ($blockinfo->{revavail} || $blockinfo->{revpartial}) );
    my $cached;
    # Get rDNS info;  duplicates a bit of getBlockData but also does the RPC call if possible
    ($blockinfo->{rdns},$cached) = getBlockRDNS($ip_dbh, id => $webvar{id}, type => $blockinfo->{type}, user => $authuser);
    $page->param(rdns     => $blockinfo->{rdns});
    # visual flag that we're working IPDB-local, not off more authoritative data in dnsadmin
    $page->param(cached   => $cached);

    # Limit the per-IP rDNS list based on CIDR length;  larger ones just take up too much space.
    # Also, don't show on IP pools;  the individual IPs will have a space for rDNS
    # Don't show on single IPs;  these use the "pattern" field
    if ($IPDBacl{$authuser} =~ /c/
        && $cidr->masklen != $cidr->bits
        && ($cidr->bits - $cidr->masklen) <= $IPDB::maxrevlist
        && $blockinfo->{type} !~ /^.[dpi]/
        # do we want to allow v6 at all?
        #&& ! $cidr->{isv6}
        ) {
      $page->param(r_iplist => getRDNSbyIP($ip_dbh, id => $webvar{id}, type => $blockinfo->{type},
          range => $blockinfo->{block}, user => $authuser) );
    }
  } # rDNS availability check

  # consider extending this to show time as well as date
  my ($lastmod,undef) = split /\s+/, $blockinfo->{lastmod};
  $page->param(lastmod  => $lastmod);

  $page->param(block    => $blockinfo->{block});
  $page->param(city     => $blockinfo->{city});
  $page->param(custid   => $blockinfo->{custid});

##fixme The check here should be built from the database
# Need to expand to support pool types too
  if ($blockinfo->{type} =~ /^.[ne]$/ && $IPDBacl{$authuser} =~ /c/) {
    $page->param(changetype => 1);
    $page->param(alloctype => [
		{ selme => ($blockinfo->{type} eq 'me'), type => "me", disptype => "Dialup netblock" },
		{ selme => ($blockinfo->{type} eq 'de'), type => "de", disptype => "Dynamic DSL netblock" },
		{ selme => ($blockinfo->{type} eq 'ce'), type => "ce", disptype => "Dynamic cable netblock" },
		{ selme => ($blockinfo->{type} eq 'we'), type => "we", disptype => "Dynamic wireless netblock" },
		{ selme => ($blockinfo->{type} eq 'cn'), type => "cn", disptype => "Customer netblock" },
		{ selme => ($blockinfo->{type} eq 'en'), type => "en", disptype => "End-use netblock" },
		{ selme => ($blockinfo->{type} eq 'in'), type => "in", disptype => "Internal netblock" },
		]
	);
  } else {
    $page->param(disptype => $disp_alloctypes{$blockinfo->{type}});
    $page->param(type => $blockinfo->{type});
  }

## node hack
  my ($nodeid,$nodename) = getNodeInfo($ip_dbh, $blockinfo->{block});
#  $page->param(havenodeid => $nodeid);
  $page->param(nodename => $nodename);

##fixme:  this whole hack needs cleanup and generalization for all alloctypes
##fixme:  arguably a bug that presence of a nodeid implies it can be changed..
  if ($IPDBacl{$authuser} =~ /c/) {
    my $nlist = getNodeList($ip_dbh);
    if ($nodeid) {
      foreach (@{$nlist}) {
        $$_{selme} = ($$_{node_id} == $nodeid);
      }
    }
    $page->param(nodelist => $nlist);
  }
## end node hack

  $page->param(vrf      => $blockinfo->{vrf});
  $page->param(vlan     => $blockinfo->{vlan});

  # Reserved-for-expansion
  $page->param(reserve  => $blockinfo->{reserve});
  $page->param(reserve_id => $blockinfo->{reserve_id});
  my $newblock = NetAddr::IP->new($cidr->addr, $cidr->masklen - 1)->network;
  $page->param(newblock => $newblock);

  # not happy with the upside-down logic, but...
  $page->param(swipable => $blockinfo->{type} !~ /.i/);
  $page->param(swip     => $blockinfo->{swip} ne 'n') if $blockinfo->{swip};

  $page->param(circid   => $blockinfo->{circuitid});
  $page->param(desc     => $blockinfo->{description});
  $page->param(notes    => $blockinfo->{notes});

  # Check to see if we can display sensitive data
  $page->param(nocling  => $IPDBacl{$authuser} =~ /s/);
  $page->param(privdata => $blockinfo->{privdata});

  # ACL trickery - these two template booleans control the presence of all form/input tags
  $page->param(maychange => $IPDBacl{$authuser} =~ /c/);
  $page->param(maydel => $IPDBacl{$authuser} =~ /d/);

  # Need to find internal knobs to twist to actually vary these.  (Ab)use "change" flag for now
  $page->param(maymerge => ($IPDBacl{$authuser} =~ /c/ && $blockinfo->{type} !~ /^.i$/));
  if ($IPDBacl{$authuser} =~ /c/ && $blockinfo->{type} !~ /^.i$/) {
    if ($blockinfo->{type} =~ /^.p$/) {
      # PPP pools
      $page->param(maysplit => 1) if $cidr->masklen+1 < $cidr->bits;
    } elsif ($blockinfo->{type} =~ /.d/) {
      # Non-PPP pools
      $page->param(maysplit => 1) if $cidr->masklen+2 < $cidr->bits;
    } else {
      # Standard netblocks.  Arguably allowing splitting these down to single IPs
      # doesn't make much sense, but forcing users to apply allocation types
      # "properly" is worse than herding cats.
      $page->param(maysplit => 1) if $cidr->masklen < $cidr->bits;
    }
  }

} # edit()


# Stuff new info about a block into the db
# action=update
sub update {
  if ($IPDBacl{$authuser} !~ /c/) {
    $aclerr = 'updateblock';
    return;
  }

  # Collect existing block info here, since we need it for the breadcrumb nav
  my $binfo = getBlockData($ip_dbh, $webvar{block}, $webvar{basetype});
  my $crumbs = getBreadCrumbs($ip_dbh, $binfo->{parent_id});
  my @rcrumbs = reverse (@$crumbs);
  $utilbar->param(breadcrumb => \@rcrumbs);

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

  $webvar{swip} = 'n' if !$webvar{swip};

  my %updargs = (
	custid		=> $webvar{custid},
	city		=> $webvar{city},
	description	=> $webvar{desc},
	notes		=> $webvar{notes},
	circuitid	=> $webvar{circid},
	block		=> $webvar{block},
	type		=> $webvar{alloctype},
	swip		=> $webvar{swip},
	rdns		=> $webvar{rdns},
	vrf		=> $webvar{vrf},
	vlan		=> $webvar{vlan},
	user		=> $authuser,
	);

  # Semioptional values
  $updargs{privdata} = $webvar{privdata} if $IPDBacl{$authuser} =~ /s/;
  $updargs{node} = $webvar{node} if $webvar{node};

  # collect per-IP rDNS fields.  only copy over the ones that actually have something in them.
  my %iprev;
  foreach (keys %webvar) {
    $iprev{$_} = $webvar{$_} if /host_[\d.a-fA-F:]+/ && $webvar{$_};
  }

  # Merge with reserved freeblock
  $updargs{fbmerge} = $webvar{expandme} if $webvar{expandme};

  my ($code,$msg) = updateBlock($ip_dbh, %updargs, iprev => \%iprev);

  if ($code eq 'FAIL') {
    syslog "err", "$authuser could not update block/IP '$webvar{block}': '$msg'";
    $page->param(err => "Could not update block/IP $webvar{block}: $msg");
    return;
  }

  # If we get here, the operation succeeded.
  syslog "notice", "$authuser updated $webvar{block}";
##fixme:  log details of the change?  old way is in the .debug stream anyway.
##fixme:  need to wedge something in to allow "update:field" notifications
## hmm.  how to tell what changed?  O_o
mailNotify($ip_dbh, 's:swi', "SWIPed: $disp_alloctypes{$webvar{alloctype}} $webvar{block}",
	"$webvar{block} had SWIP status changed to \"Yes\" by $authuser") if $webvar{swip} eq 'on';

## node hack
  if ($webvar{node} && $webvar{node} ne '-') {
    my $nodename = getNodeName($ip_dbh, $webvar{node});
    $page->param(nodename => $nodename);
  }
## end node hack

  # Link back to browse-routed or list-pool page on "Update complete" page.
  my $pblock = getBlockData($ip_dbh, $binfo->{parent_id});
  $page->param(backid => $binfo->{parent_id});
  $page->param(backblock => $pblock->{block});
  $page->param(backpool => ($webvar{basetype} eq 'i'));

  # Do some HTML fiddling here instead of using ESCAPE=HTML in the template,
  # because otherwise we can't convert \n to <br>.  *sigh*
  $webvar{notes} = $q->escapeHTML($webvar{notes});	# escape first...
  $webvar{notes} =~ s/\n/<br>\n/;			# ... then convert newlines
  $webvar{privdata} = ($webvar{privdata} ? $q->escapeHTML($webvar{privdata}) : "&nbsp;");
  $webvar{privdata} =~ s/\n/<br>\n/;

  if ($webvar{expandme}) {
    # this is fugly but still faster than hitting the DB again with getBlockData()
    my $tmp = new NetAddr::IP $binfo->{block};
    my $fb = new NetAddr::IP $binfo->{reserve};
    my @newblock = $tmp->compact($fb);
    $page->param(cidr => $newblock[0]);
  } else {
    $page->param(cidr => $binfo->{block});
  }
  $page->param(rdns => $webvar{rdns});
  $page->param(city => $webvar{city});
  $page->param(disptype => $disp_alloctypes{$webvar{alloctype}});
  $page->param(custid => $webvar{custid});
  $page->param(swip => $webvar{swip} eq 'on' ? 'Yes' : 'No');
  $page->param(circid => $webvar{circid});
  $page->param(desc => $webvar{desc});
  $page->param(notes => $webvar{notes});
  $page->param(privdata => $webvar{privdata})
	if $IPDBacl{$authuser} =~ /s/;

} # update()


sub prepSplit {
  if ($IPDBacl{$authuser} !~ /c/) {
    $aclerr = 'splitblock';
    return;
  }

  my $blockinfo = getBlockData($ip_dbh, $webvar{block});

  # Tree navigation
  my $crumbs = getBreadCrumbs($ip_dbh, $blockinfo->{parent_id});
  my @rcrumbs = reverse (@$crumbs);
  $utilbar->param(breadcrumb => \@rcrumbs);

  if ($blockinfo->{type} =~ /^.i$/) {
    $page->param(err => "Can't split a single IP allocation");
    return;
  }

  # Info about current allocation
  $page->param(oldblock => $blockinfo->{block});
  $page->param(block => $webvar{block});

# Note that there are probably different rules that should be followed to restrict splitting IPv6 blocks;
# strictly speaking it will be exceptionally rare to see smaller than a /64 assigned to a customer, since that
# breaks auto-addressing schemes.

  # Generate possible splits
  my $block = new NetAddr::IP $blockinfo->{block};
  my $oldmask = $block->masklen;
  if ($blockinfo->{type} =~ /^.d$/) {
    # Non-PPP pools
    $page->param(ispool => 1);
    if ($oldmask+2 >= $block->bits) {
      $page->param(err => "Can't split a standard netblock pool any further");
      return;
    }
    # Allow splitting down to v4 /30 (which results in one usable IP;  dubiously useful)
    $page->param(sp4mask => $oldmask+2) if $oldmask+2 <= $block->bits-2;
  } elsif ($blockinfo->{type} =~ /.p/) {
    $page->param(ispool => 1);
    # Allow splitting PPP pools down to v4 /31
    $page->param(sp4mask => $oldmask+2) if $oldmask+2 <= $block->bits-1;
  } else {
    # Allow splitting all other non-pool netblocks down to single IPs, which...
    # arguably should be *aggregated* in a pool.  Except where they shouldn't.
    $page->param(sp4mask => $oldmask+2) if $oldmask+2 <= $block->bits;
  }
  # set the split-in-half mask
  $page->param(sp2mask => $oldmask+1);

  # Generate possible shrink targets
  my @keepers = $block->split($block->masklen+1);
  $page->param(newblockA => $keepers[0]);
  $page->param(newblockB => $keepers[1]);
} # prepSplit()


sub doSplit {
  if ($IPDBacl{$authuser} !~ /c/) {
    $aclerr = 'splitblock';
    return;
  }

##fixme:  need consistent way to identify "this thing that is this thing" with only the ID
# also applies to other locations
  my $blockinfo = getBlockData($ip_dbh, $webvar{block});

  # Tree navigation
  my $crumbs = getBreadCrumbs($ip_dbh, $blockinfo->{parent_id});
  my @rcrumbs = reverse (@$crumbs);
  $utilbar->param(breadcrumb => \@rcrumbs);

  if ($blockinfo->{type} =~ /^.i$/) {
    $page->param(err => "Can't split a single IP allocation");
    return;
  }

  if ($webvar{subact} eq 'split') {
    $page->param(issplit => 1);
    my $block = new NetAddr::IP $blockinfo->{block};
    my $newblocks = splitBlock($ip_dbh, id => $webvar{block}, basetype => 'b', newmask => $webvar{split},
	user => $authuser);
    if ($newblocks) {
      $page->param(newblocks => $newblocks);
    } else {
      $page->param(err => $IPDB::errstr);
    }

  } elsif ($webvar{subact} eq 'shrink') {
    $page->param(nid => $webvar{block});
    $page->param(newblock => $webvar{shrink});
    my $newfree = shrinkBlock($ip_dbh, $webvar{block}, $webvar{shrink});
    if ($newfree) {
      $page->param(newfb => $newfree);
    } else {
      $page->param(err => $IPDB::errstr);
    }

  } else {
    # Your llama is on fire.
    $page->param(err => "Missing form field that shouldn't be missing.");
    return;
  }

  # common bits
  $page->param(cidr => $blockinfo->{block});
  # and the backlink to the parent container
  my $pinfo = getBlockData($ip_dbh, $blockinfo->{parent_id});
  $page->param(backid => $blockinfo->{parent_id});
  $page->param(backblock => $pinfo->{block});
} # doSplit()


# Set up for merge
sub prepMerge {
  my $binfo = getBlockData($ip_dbh, $webvar{block});

  # Tree navigation
  my $crumbs = getBreadCrumbs($ip_dbh, $binfo->{parent_id});
  my @rcrumbs = reverse (@$crumbs);
  $utilbar->param(breadcrumb => \@rcrumbs);

  $page->param(block => $webvar{block});
  $page->param(ispool => $binfo->{type} =~ /.[dp]/);
  $page->param(ismaster => $binfo->{type} eq 'mm');
  $page->param(oldblock => $binfo->{block});
  $page->param(oldtype => $disp_alloctypes{$binfo->{type}});
  $page->param(typelist => getTypeList($ip_dbh, 'n', $binfo->{type}));  # down the rabbit hole we go...

  # Strings for scope;  do this way so we don't have to edit them many places
  $page->param(vis_keepall => $merge_display{keepall});
  $page->param(vis_mergepeer => $merge_display{mergepeer});
  $page->param(vis_clearpeer => $merge_display{clearpeer});
  $page->param(vis_clearall => $merge_display{clearall});

} # prepMerge()


# Show what will be merged, present warnings about data loss
sub confMerge {
  if (!$webvar{newmask} || $webvar{newmask} !~ /^\d+$/) {
    $page->param(err => 'New netmask required');
    return;
  }

  $page->param(block => $webvar{block});
  my $binfo = getBlockData($ip_dbh, $webvar{block});
  my $pinfo = getBlockData($ip_dbh, $binfo->{parent_id});
  my $minfo = getBlockData($ip_dbh, $binfo->{master_id});
  my $block = new NetAddr::IP $binfo->{block};

  # Tree navigation
  my $crumbs = getBreadCrumbs($ip_dbh, $binfo->{parent_id});
  my @rcrumbs = reverse (@$crumbs);
  $utilbar->param(breadcrumb => \@rcrumbs);

  $page->param(oldblock => $binfo->{block});
  $page->param(oldtype => $disp_alloctypes{$binfo->{type}});
  $page->param(ismaster => $binfo->{type} eq 'mm');
  $page->param(ispool => $webvar{alloctype} =~ /.[dp]/);
  $page->param(isleaf => $webvar{alloctype} =~ /.[enr]/);
  $page->param(newtype => $webvar{alloctype});
  $page->param(newdisptype => $disp_alloctypes{$webvar{alloctype}});
  my $newblock = new NetAddr::IP $block->addr."/$webvar{newmask}";
  $newblock = $newblock->network;
  $page->param(newmask => $webvar{newmask});
  $page->param(newblock => "$newblock");

  # get list of allocations and freeblocks to be merged
  my $malloc_list = listForMerge($ip_dbh, $binfo->{parent_id}, $newblock, 'a');
  $page->param(mergealloc => $malloc_list);

  $page->param(vis_scope => $merge_display{$webvar{scope}});
  $page->param(scope => $webvar{scope});
} # confMerge()


# Make it so
sub doMerge {
  if (!$webvar{newmask} || $webvar{newmask} !~ /^\d+$/) {
    $page->param(err => 'New netmask required');
    return;
  }

  $page->param(block => $webvar{block});
  my $binfo = getBlockData($ip_dbh, $webvar{block});
  my $pinfo = getBlockData($ip_dbh, $binfo->{parent_id});
  my $block = new NetAddr::IP $binfo->{block};

  # Tree navigation
  my $crumbs = getBreadCrumbs($ip_dbh, $binfo->{parent_id});
  my @rcrumbs = reverse (@$crumbs);
  $utilbar->param(breadcrumb => \@rcrumbs);

  $page->param(oldblock => $binfo->{block});
  $page->param(oldtype => $disp_alloctypes{$binfo->{type}});
  $page->param(newdisptype => $disp_alloctypes{$webvar{newtype}});
  my $newblock = new NetAddr::IP $block->addr."/$webvar{newmask}";
  $newblock = $newblock->network;
  $page->param(newblock => $newblock);
  $page->param(vis_scope => $merge_display{$webvar{scope}});

  my $mlist = mergeBlocks($ip_dbh, $webvar{block}, %webvar, user => $authuser);

  if ($mlist) {
    #(newtype => $webvar{newtype}, newmask => $webvar{newmask}));
    # Slice off first entry (the new parent - note this may be a new allocation,
    # not the same ID that was "merged"!
    my $parent = shift @$mlist;
    $page->param(backpool => $webvar{newtype} =~ /.[dp]/);
    if ($webvar{newtype} =~ /.[enr]/) {
      $page->param(backleaf => 1);
      $page->param(backid => $binfo->{parent_id});
      $page->param(backblock => $pinfo->{block});
    } else {
      $page->param(backid => $parent->{id});
      $page->param(backblock => $parent->{block});
    }
    $page->param(mergelist => $mlist);
  } else {
    $page->param(err => "Merge failed: $IPDB::errstr");
  }
} # doMerge()


# Delete an allocation.
sub remove {
  if ($IPDBacl{$authuser} !~ /d/) {
    $aclerr = 'delblock';
    return;
  }

  # Serves'em right for getting here...
  if (!defined($webvar{block})) {
    $page->param(err => "Can't delete a block that doesn't exist");
    return;
  }

  my $blockdata;
  $blockdata = getBlockData($ip_dbh, $webvar{block}, $webvar{basetype});

  # Tree navigation
  my $crumbs = getBreadCrumbs($ip_dbh, $blockdata->{parent_id});
  my @rcrumbs = reverse (@$crumbs);
  $utilbar->param(breadcrumb => \@rcrumbs);

  if ($blockdata->{parent_id} == 0) {	# $webvar{alloctype} eq 'mm'
    $blockdata->{city} = "N/A";
    $blockdata->{custid} = "N/A";
    $blockdata->{circuitid} = "N/A";
    $blockdata->{description} = "N/A";
    $blockdata->{notes} = "N/A";
    $blockdata->{privdata} = "N/A";
  } # end cases for different alloctypes

  $page->param(blockid => $webvar{block});
  $page->param(basetype => $webvar{basetype});

  $page->param(block => $blockdata->{block});
  $page->param(rdns => $blockdata->{rdns});

  # maybe need to apply more magic here?
  # most allocations we *do* want to autodelete the forward as well as reverse;  for a handful we don't.
  # -> all real blocks (nb: pool IPs need extra handling)
  # -> NOC/private-IP (how to ID?)
  # -> anything with a pattern matching $IPDB::domain?
  if ($blockdata->{type} !~ /^.i$/) {
    $page->param(autodel => 1);
  }

  $page->param(disptype => $disp_alloctypes{$blockdata->{type}});
  $page->param(city => $blockdata->{city});
  $page->param(custid => $blockdata->{custid});
  $page->param(circid => $blockdata->{circuitid});
  $page->param(desc => $blockdata->{description});
  $blockdata->{notes} = $q->escapeHTML($blockdata->{notes});
  $blockdata->{notes} =~ s/\n/<br>\n/;
  $page->param(notes => $blockdata->{notes});
  $blockdata->{privdata} = $q->escapeHTML($blockdata->{privdata});
  $blockdata->{privdata} = '&nbsp;' if !$blockdata->{privdata};
  $blockdata->{privdata} =~ s/\n/<br>\n/;
  $page->param(privdata => $blockdata->{privdata}) if $IPDBacl{$authuser} =~ /s/;
  $page->param(delpool => $blockdata->{type} =~ /^.[pd]$/);

} # end remove()


# 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/) {
    $aclerr = 'delblock';
    return;
  }

  # need to retrieve block data before deleting so we can notify on that
  my $blockinfo = getBlockData($ip_dbh, $webvar{block}, $webvar{basetype});
  my $pinfo = getBlockData($ip_dbh, $blockinfo->{parent_id}, 'b');

  # Tree navigation
  my $crumbs = getBreadCrumbs($ip_dbh, $blockinfo->{parent_id});
  my @rcrumbs = reverse (@$crumbs);
  $utilbar->param(breadcrumb => \@rcrumbs);

  my ($code,$msg) = deleteBlock($ip_dbh, $webvar{block}, $webvar{basetype}, $webvar{delforward}, $authuser);

  $page->param(block => $blockinfo->{block});
  $page->param(bdisp => $q->escapeHTML($disp_alloctypes{$blockinfo->{type}}));
  $page->param(delparent_id => $blockinfo->{parent_id});
  if ($pinfo) {
    $page->param(delparent => $pinfo->{block});
    $page->param(pdisp => $q->escapeHTML($disp_alloctypes{$pinfo->{type}}));
  }
  $page->param(returnpool => ($webvar{basetype} eq 'i') );
  if ($code =~ /^WARN(POOL|MERGE)/) {
    my ($pid,$pcidr) = split /,/, $msg;
    my $real_pinfo = getBlockData($ip_dbh, $pid, 'b');
    $page->param(parent_id => $pid);
    $page->param(parent => $pcidr);
    $page->param(real_disp => $q->escapeHTML($disp_alloctypes{$real_pinfo->{type}}));
    $page->param(mergeip => $code eq 'WARNPOOL');
  }
  if ($code eq 'WARN') {
    $msg =~ s/\n/<br>\n/g;
    $page->param(genwarn => $msg);
  }
  if ($code eq 'OK' || $code =~ /^WARN/) {
    syslog "notice", "$authuser deallocated '".$blockinfo->{type}."'-type netblock $webvar{block} ".
	$blockinfo->{custid}.", ".$blockinfo->{city}.", desc='".$blockinfo->{description}."'";
    mailNotify($ip_dbh, 'da', "REMOVED: ".$disp_alloctypes{$blockinfo->{type}}." $webvar{block}",
	$disp_alloctypes{$blockinfo->{type}}." $webvar{block} deallocated by $authuser\n".
	"CustID: ".$blockinfo->{custid}."\nCity: ".$blockinfo->{city}.
	"\nDescription: ".$blockinfo->{description}."\n");
  } else {
    $page->param(failmsg => $msg);
    if ($webvar{alloctype} =~ /^.i$/) {
      syslog "err", "$authuser could not deallocate static IP '$webvar{block}': '$msg'";
    } else {
      syslog "err", "$authuser could not deallocate netblock '$webvar{block}': '$msg'";
      $page->param(netblock => 1);
    }
  }

} # finalDelete
