#!/usr/bin/perl
# ipdb/cgi-bin/combineblocks.pl
# Quick hack to clean up mangled deallocations
###
# Revision info
# $Date$
# SVN revision $Rev$
# Last update by $Author$
###

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

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

# push "the directory the script is in" into @INC
use FindBin;
use lib "$FindBin::RealBin/";

use MyIPDB;

my $null = new NetAddr::IP "255.255.255.255/32";

my @fbtypes;

my ($dbh,$ret) = connectDB_My;
initIPDBGlobals($dbh);
my $sth;

# Get the types of freeblocks
$sth = $dbh->prepare("select distinct routed from freeblocks");
$sth->execute;
while (my @data = $sth->fetchrow_array) {
  push @fbtypes, @data;
}

foreach my $type (@fbtypes) {

  my $i=0;
  my @compacted;

  my $sth = $dbh->prepare("select cidr from freeblocks where routed='$type'");
  $sth->execute;
  while (my @data = $sth->fetchrow_array) {
    my $temp = new NetAddr::IP $data[0];
    @compacted = $temp->compact(@compacted);
    $i++;
  }

#print $compacted[0];
my $numcomp = @compacted;
#print " $numcomp";

  if ($i == $numcomp) {
    print "No compactable blocks for type $type ($i free)\n";
    next;
  }
  print "Type $type: $i free blocks to start, $numcomp to finish\n";

  $sth = $dbh->prepare("select cidr from freeblocks where cidr << ?");
  foreach my $cip (@compacted) {
    $sth->execute("$cip");
    if ($sth->rows > 0) {
      print "  $cip combines from:\n";
      while (my @data = $sth->fetchrow_array) {
        print "    $data[0]\n";
      }
#    } else {
#      print "  $cip does not compact\n";
    }
  }

} # each @fbtype

finish($dbh);
