Index: trunk/cgi-bin/admin.cgi
===================================================================
--- trunk/cgi-bin/admin.cgi	(revision 146)
+++ trunk/cgi-bin/admin.cgi	(revision 199)
@@ -17,5 +17,5 @@
 use DBI;
 use CommonWeb qw(:ALL);
-use IPDB qw(:ALL);
+use MyIPDB;
 #use POSIX qw(ceil);
 use NetAddr::IP;
@@ -43,44 +43,45 @@
 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) {
+  printAndExit("Database error: $errstr\n");
+}
+initIPDBGlobals($ip_dbh);
+
 my %webvar = parse_post();
 cleanInput(\%webvar);
 
-my %full_alloc_types = (
-	"ci","Cable pool IP",
-	"di","DSL pool IP",
-	"si","Server pool IP",
-	"mi","Static dialup IP",
-	"wi","Static wireless IP",
-	"cp","Cable pool",
-	"dp","DSL pool",
-	"sp","Server pool",
-	"mp","Static dialup pool",
-	"wp","Static wireless pool",
-	"dn","Dialup netblock",
-	"dy","Dynamic DSL netblock",
-	"dc","Dynamic cable netblock",
-	"cn","Customer netblock",
-	"ee","End-use netblock",
-	"rr","Routed netblock",
-	"ii","Internal netblock",
-	"mm","Master block"
-);
-
-my $ip_dbh = connectDB;
-my $sth;
-
 print "Content-type: text/html\n\n".
-	"<html>\n<head>\n\t<title>TEST [IPDB admin tools] TEST</title>\n</head>\n<body>\n".
+	"<html>\n<head>\n\t<title>TEST [IPDB admin tools] TEST</title>\n".
+	qq(\t<link rel="stylesheet" type="text/css" href="/ip/ipdb.css">\n).
+	"</head>\n<body>\n".
 	"<h2>IPDB - Administrative Tools</h2>\n<hr>\n";
 
 if(!defined($webvar{action})) {
   $webvar{action} = "<NULL>";   #shuts up the warnings.
+
+  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";
+  }
+
   print qq(WARNING:  There are FAR fewer controls on what you can do here.  Use the
 main interface if at all possible.
-<hr><form action="admin.cgi" method="POST">
+<hr>
+<a href="admin.cgi?action=newalloc">Add allocation</a>
+<hr>
+<form action="admin.cgi" method="POST">
 <input type=hidden name=action value=alloc>
-Allocate block from this /24: <input name=allocfrom>
-<input type=submit value="List available free blocks">
-</form>
+Allocate block/IP: <input name=cidr> as <select name=alloctype>$typelist</select> to <input name=custid>
+<input type=submit value=" GIMME!! "></form>
 <hr><form action="admin.cgi" method="POST">
 <input type=hidden name=action value=alloctweak>
@@ -94,7 +95,115 @@
 }
 
+
+## Possible actions.
 if ($webvar{action} eq 'alloc') {
-  fix_allocfrom();
-  showfree($webvar{allocfrom});
+  # OK, we know what we're allocating.
+
+  if ($webvar{cidr} !~ /^\s*(\d{1,3}\.){3}\d{1,3}(\/\d{2})?\s*$/) {
+    printAndExit("Can't allocate something that's not a netblock/ip");
+  }
+
+  $sth = $ip_dbh->prepare("select def_custid from alloctypes where type='$webvar{alloctype}'");
+  $sth->execute;
+  my @data = $sth->fetchrow_array;
+  my $custid = $data[0];
+  if ($custid eq '') {
+    # Type that doesn't have a default custid
+    $custid = $webvar{custid};
+  }
+##fixme Check billing DB here
+
+  my $cidr = new NetAddr::IP $webvar{cidr};
+  my @data;
+  if ($webvar{alloctype} eq 'rm') {
+    $sth = $ip_dbh->prepare("select cidr from freeblocks where cidr >>='$cidr' and routed='n'");
+    $sth->execute;
+    @data = $sth->fetchrow_array;
+# User deserves errors if user can't be bothered to find the free block first.
+    printAndExit("Can't allocate from outside a free block!!\n")
+        if !$data[0];
+  } else {
+    $sth = $ip_dbh->prepare("select cidr from freeblocks where cidr >>='$cidr' and not (routed='n')");
+    $sth->execute;
+    @data = $sth->fetchrow_array;
+# User deserves errors if user can't be bothered to find the free block first.
+    printAndExit("Can't allocate from outside a routed block!!\n")
+        if !$data[0];
+  }
+
+  my $alloc_from = new NetAddr::IP $data[0];
+  $sth->finish;
+
+  my $cities = '';
+  foreach my $city (@citylist) {
+    $cities .= "<option>$city</option>\n";
+  }
+
+  print qq(<table class=regular>
+<form method=POST action=admin.cgi>
+<tr class=color1>
+<td>Allocating:</td>
+<td>$cidr<input type=hidden name=cidr value="$cidr"></td>
+</tr><tr class=color2>
+<td>Type:</td><td>$disp_alloctypes{$webvar{alloctype}}
+<input type=hidden name=alloctype value="$webvar{alloctype}"></td>
+</tr><tr class=color1>
+<td>Allocated from:</td>
+<td>$alloc_from<input type=hidden name=alloc_from value="$alloc_from"></td>
+</tr><tr class="color2">
+<td>Customer ID:</td><td>$custid<input type=hidden name=custid value="$custid"></td>
+</tr><tr class=color1>
+<td>Customer location:</td><td>
+<select name="city"><option selected>-</option>
+$cities
+</select>
+&nbsp;<a href="javascript:popNotes('/ip/newcity.html')">Add new location</a>
+</td>
+</tr>
+<tr class="color2">
+<td>Circuit ID:</td><td><input name=circid size=40></td>
+</tr><tr class="color1">
+<td>Description/Name:</td><td><input name="desc" size=40></td>
+</tr><tr class="color2">
+<td>Notes:</td><td><textarea name="notes" rows="3" cols="40"></textarea></td>
+</tr><tr class="warning">
+<td colspan=2><center>WARNING:  This will IMMEDIATELY assign this block!!</center></td>
+</tr><tr class="color2">
+<td class="center" colspan="2"><input type="submit" value="  Assign  "></td>
+<input type="hidden" name="action" value="confirm">
+</tr>
+</table>
+);
+
+
+} elsif ($webvar{action} eq 'confirm') {
+
+  print "Assigning $webvar{cidr} to $webvar{custid} (\"$webvar{desc}\") as ".
+	"$disp_alloctypes{$webvar{alloctype}}...<br>\n";
+  # Only need to check city here.
+  if ($webvar{city} eq '-') {
+    printError("Invalid customer location!  Go back and select customer's location.");
+  } else {
+    my ($retcode,$msg) = allocateBlock($ip_dbh, $webvar{cidr}, $webvar{alloc_from},
+	$webvar{custid}, $webvar{alloctype}, $webvar{city}, $webvar{desc}, $webvar{notes},
+	$webvar{circid});
+    if ($retcode eq 'OK') {
+      print "Allocation OK!\n";
+
+      if ($webvar{alloctype} =~ /^.i$/) {
+        # Notify tech@example.com
+        mailNotify('tech@example.com',"$disp_alloctypes{$webvar{alloctype}} allocation",
+          "$disp_alloctypes{$webvar{alloctype}} $msg allocated to customer $webvar{custid}\n".
+          "Description: $webvar{desc}\n\nAllocated by: $authuser\n");
+      }
+      syslog "notice", "$authuser allocated '$webvar{cidr}' to '$webvar{custid}' as ".
+	"'$webvar{alloctype}'";
+    } else {
+      print "Allocation failed!  IPDB::allocateBlock said:\n$msg\n";
+      syslog "err", "($authuser) Allocation of '$webvar{cidr}' to '$webvar{custid}' as ".
+	"'$webvar{type}' failed: '$msg'";
+    }
+  } # done city check
+
 } elsif ($webvar{action} eq 'alloctweak') {
   fix_allocfrom();
@@ -119,13 +228,8 @@
 
   print $html;
-} elsif ($webvar{action} eq 'confirm') {
-  print "Assigning $webvar{block} to $webvar{custid} (\"$webvar{desc}\")...\n";
-  allocBlock($ip_dbh, $webvar{allocfrom}, $webvar{block}, $webvar{alloctype},
-	$webvar{custid}, $webvar{city}, $webvar{desc}, $webvar{notes});
-  #my ($dbh,from,block,$type,$custid,$city,$desc,$notes) = @_;
 } elsif ($webvar{action} eq 'showpools') {
   print "IP Pools currently allocated:\n".
 	"<table border=1>\n<tr><td>Pool</td><td># of free IPs</td></tr>\n";
-  $sth = $ip_dbh->prepare("select cidr from allocations where type like '%p' order by cidr");
+  $sth = $ip_dbh->prepare("select cidr from allocations where type like '%p' or type like '%d' order by cidr");
   $sth->execute;
   my %poolfree;
@@ -146,6 +250,7 @@
   showPool($webvar{pool});
 } elsif ($webvar{action} eq 'updatepool') {
+
   $sth = $ip_dbh->prepare("update poolips set custid='$webvar{custid}', ".
-	"city='$webvar{city}', ptype='$webvar{ptype}', available='".
+	"city='$webvar{city}', type='$webvar{type}', available='".
 	(($webvar{available} eq 'y') ? 'y' : 'n').
 	"', notes='$webvar{notes}', description='$webvar{desc}' ".
@@ -162,5 +267,5 @@
     syslog "notice", "$authuser updated pool IP $webvar{ip}";
   }
-  showPool("$data[0]");
+#  showPool("$data[0]");
 #} else {
 #  print "webvar{action} check failed: $webvar{action}";
@@ -189,96 +294,4 @@
     $webvar{allocfrom} .= "/24";
   }
-}
-
-
-# Do the gruntwork of allocating a block.  This should really be in IPDB.pm.
-sub allocBlock($$$$$$$$) {
-  my ($dbh,undef,undef,$type,$custid,$city,$desc,$notes) = @_;
-  my $from = new NetAddr::IP $_[1];
-  my $block = new NetAddr::IP $_[2];
-
-  local $ip_dbh->{AutoCommit} = 0;  # enable transactions, if possible
-  local $ip_dbh->{RaiseError} = 1;  # Use local to limit to this sub
-
-  if ($from eq $block) {
-    eval {
-      # common stuff for end-use, dialup, dynDSL, pools, etc, etc.
-
-      $sth = $ip_dbh->prepare("delete from freeblocks where cidr='$block'");
-      $sth->execute;
-
-      # Insert the allocations entry
-      $sth = $ip_dbh->prepare("insert into allocations values ('$block',".
-	"'$custid','$type','$city','$desc','$notes',".$block->masklen.")");
-      $sth->execute;
-
-      $ip_dbh->commit;
-    };  # end of eval
-    if ($@) {
-      carp "Transaction aborted because $@";
-      eval { $ip_dbh->rollback; };
-      syslog "err", "Allocation of '$webvar{fullcidr}' to '$webvar{custid}' as ".
-	"'$webvar{alloctype}' by $authuser failed: '$@'";
-      printAndExit("Allocation of $cidr as $full_alloc_types{$webvar{alloctype}} failed.\n");
-    } else {
-      syslog "notice", "$authuser allocated '$block' to '$custid'".
-	" as '$webvar{alloctype}'";
-      print "Block $block allocated to $custid.<br>\n";
-    }
-  } else {
-    # The complex case.  An allocation from a larger block.
-    
-    # Gotta snag the free blocks left over.
-    my $wantmaskbits = $block->masklen;
-    my $maskbits = $from->masklen;
-
-    my @newfreeblocks;	# Holds free blocks generated from splitting the source freeblock.
-
-    my $i=0;
-    my $tmp_from = $from;	# So we don't munge $from
-    while ($maskbits++ < $wantmaskbits) {
-      my @subblocks = $tmp_from->split($maskbits);
-      $newfreeblocks[$i++] = (($block->within($subblocks[0])) ? $subblocks[1] : $subblocks[0]);
-      $tmp_from = ( ($block->within($subblocks[0])) ? $subblocks[0] : $subblocks[1] );
-    } # while
-
-# insert the data here.  Woo.
-    # Begin SQL transaction block
-    eval {
-      # Delete old freeblocks entry
-      $sth = $ip_dbh->prepare("delete from freeblocks where cidr='$from'");
-      $sth->execute();
-
-      # Insert the new freeblocks entries
-      $sth = $ip_dbh->prepare("insert into freeblocks values (?, ?, ".
-	"(select city from routed where cidr >>= '$block'),'y')");
-      foreach my $block (@newfreeblocks) {
-	$sth->execute("$block", $block->masklen);
-      }
-      # Insert the allocations entry
-      $sth = $ip_dbh->prepare("insert into allocations values ('$block',".
-	"'$custid','$type','$city','$desc','$notes',".$block->masklen.")");
-      $sth->execute;
-
-      $ip_dbh->commit;
-    }; # end eval
-    if ($@) {
-      carp "Transaction aborted because $@";
-      eval { $ip_dbh->rollback; };
-      syslog "err", "Allocation of '$block' to '$custid' as ".
-	"'$type' by $authuser failed: '$@'";
-      print "Allocation of $block as $full_alloc_types{$type} failed.\n";
-    } else {
-      syslog "notice", "$authuser allocated '$block' to '$custid'".
-	" as '$type'";
-      print "Block $block allocated to $custid.<br>\n";
-    } # done OK?/NOK! check after DB changes
-
-  } # done "hard" allocation case.
-
-  # need to get /24 that block is part of
-  my @bits = split /\./, $webvar{block};
-  $bits[3] = "0/24";
-  showAllocs((join ".", @bits));
 }
 
@@ -330,14 +343,15 @@
 	(($data[2] eq 'mi') ? ' selected' : '') ." value='mi'>Static IP - Dialup</option>\n<option".
 	(($data[2] eq 'wi') ? ' selected' : '') ." value='wi'>Static IP - Wireless</option>\n<option".
-	(($data[2] eq 'sp') ? ' selected' : '') ." value='sp'>Static Pool - Server pool</option>\n<option".
-	(($data[2] eq 'cp') ? ' selected' : '') ." value='cp'>Static Pool - Cable</option>\n<option".
+	(($data[2] eq 'sd') ? ' selected' : '') ." value='sd'>Static Pool - Server pool</option>\n<option".
+	(($data[2] eq 'cd') ? ' selected' : '') ." value='cd'>Static Pool - Cable</option>\n<option".
 	(($data[2] eq 'dp') ? ' selected' : '') ." value='dp'>Static Pool - DSL</option>\n<option".
 	(($data[2] eq 'mp') ? ' selected' : '') ." value='mp'>Static Pool - Dialup</option>\n<option".
 	(($data[2] eq 'wp') ? ' selected' : '') ." value='wp'>Static Pool - Wireless</option>\n<option".
-	(($data[2] eq 'ee') ? ' selected' : '') ." value='ee'>End-use netblock</option>\n<option".
-	(($data[2] eq 'dn') ? ' selected' : '') ." value='dn'>Dialup netblock</option>\n<option".
-	(($data[2] eq 'dy') ? ' selected' : '') ." value='dy'>Dynamic DSL netblock</option>\n<option".
-	(($data[2] eq 'dc') ? ' selected' : '') ." value='dc'>Dynamic cable netblock</option>\n<option".
-	(($data[2] eq 'ii') ? ' selected' : '') ." value='ii'>Internal netblock</option>\n".
+	(($data[2] eq 'en') ? ' selected' : '') ." value='en'>End-use netblock</option>\n<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 WiFi netblock</option>\n<option".
+	(($data[2] eq 'in') ? ' selected' : '') ." value='in'>Internal netblock</option>\n".
         "</select></td>\n";
     print qq(<td><input name=city value="$data[3]"></td>\n).
@@ -391,10 +405,10 @@
 <tr><td align=right>Customer ID:</td><td><input name=custid></td></tr>
 <tr><td align=right>Customer location:</td><td><input name=city></td></tr>
-<tr><td align=right>Type:</td><td><select name=ptype><option selected>-</option>
-<option value="s">Static IP - Server pool</option>
-<option value="c">Static IP - Cable</option>
-<option value="d">Static IP - DSL</option>
-<option value="m">Static IP - Dialup</option>
-<option value="w">Static IP - Wireless</option>
+<tr><td align=right>Type:</td><td><select name=type><option selected>-</option>
+<option value="si">Static IP - Server pool</option>
+<option value="ci">Static IP - Cable</option>
+<option value="di">Static IP - DSL</option>
+<option value="mi">Static IP - Dialup</option>
+<option value="wi">Static IP - Wireless</option>
 </select></td></tr>
 <tr><td align=right>Available?</td><td><input type=checkbox value=y></td></tr>
@@ -404,5 +418,5 @@
 ).
 	"</table>Update the following record:<table border=1>\n";
-  $sth = $ip_dbh->prepare("select * from poolips where pool='$pool' order by ip");
+  $sth = $ip_dbh->prepare("select pool,ip,custid,city,type,available,description,notes from poolips where pool='$pool' order by ip");
   $sth->execute;
   while (my @data = $sth->fetchrow_array) {
