#!/usr/bin/perl
# ipdb/cgi-bin/freespace.pl
# Quick hack to calculate aggregate free IP space, and statistic-ify the blocks.
###
# SVN revision info
# $Date: 2010-06-30 21:48:03 +0000 (Wed, 30 Jun 2010) $
# SVN revision $Rev: 417 $
# Last update by $Author: kdeugau $
###
# Copyright (C) 2004-2010 - Kris Deugau

use DBI;
use NetAddr::IP;

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

use MyIPDB;

($dbh,$errstr) = connectDB_My;

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

$tnumfree = $bigrfree = $bigufree = 0;

$sql = 'select * from freeblocks where ';
# General counts first
if ($ARGV[0]) {
  $sql .= 'maskbits >= $ARGV[0] and ';
}
$sql .= "not (cidr <<= '192.168.0.0/16') ".
		"and not (cidr <<= '172.16.0.0/12') ".
		"and not (cidr <<= '10.0.0.0/8') ";
$sql .= "order by maskbits desc";

$sth = $dbh->prepare($sql);
$sth->execute;
while (@data = $sth->fetchrow_array) {
  # cidr,maskbits,city,routed
  $tnumfree++;
  $numfree{"$data[1]"}++;
}

print "Free block counts:\n";
foreach $size (sort {$a cmp $b} keys %numfree) {
  print "/$size: $numfree{$size}\n";
}
print "\n";

for ($i=30; $i>16; $i--) {
  $j = $i-1;
  $numfree{"$j"} += int $numfree{"$i"}/2;
  $numfree{"$i"} -= (int $numfree{"$i"}/2)*2;
}

print "Aggregate free space:\n";
foreach $size (sort {$a cmp $b} keys %numfree) {
  print "/$size: $numfree{$size}\n";
}
