#!/usr/bin/perl
# Import data from old IPDB to new DB
# Started 06/29/04 kdeugau@vianet

#use warnings;
#use CGI::Carp qw/fatalsToBrowser/;
use DBI;
#use DBD::Pg;
#use CommonWeb qw/:ALL/;
#use POSIX qw/ceil/;
use NetAddr::IP;

#use strict;

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

# Hardcode the masters because it's too messy and slow to
# snag them programmatically *EVERY TIME*
@masters = ((new NetAddr::IP "66.186.64.0/19"),
	(new NetAddr::IP "204.138.172.0/24"),
	(new NetAddr::IP "204.187.88.0/23"),
	(new NetAddr::IP "205.207.184.0/23"),
	(new NetAddr::IP "206.130.64.0/24"),
	(new NetAddr::IP "209.91.128.0/18"),
	(new NetAddr::IP "10.0.0.0/8"),
	(new NetAddr::IP "192.168.0.0/16"),
	);

# First step:  Slurp up data to find "master" blocks
        my $DSN  = "DBI:mysql:ipdb";
        my $user = 'root';
        my $pw   = '';
        $dbh = DBI->connect($DSN, $user, $pw) || return undef if(!$dbh);

$newdbh = DBI->connect("DBI:Pg:dbname=ipdb", "ipdb", "");

$i=0;
$sth = $dbh->prepare("select * from blocks where netmask !='/32' and netmask !='/31'");
$sth->execute;
CIDR: while (@data = $sth->fetchrow_array) {
  # data contains ipclass,netmask,subnet,city,custid,name,swip,description,notes
  $cidr = new NetAddr::IP "$data[0].$data[2]$data[1]";
  $sth2 = $newdbh->prepare("select count(*) from allocations where cidr='$cidr'");
  $sth2->execute;
if ($sth2->err) { print "err on $cidr ($data[4], $data[5]): ".$sth2->errstr."\n"; }
  @data = $sth2->fetchrow_array;
  if ($data[0] ne '1') {
    print "$cidr not found in allocations";
    $sth2 = $newdbh->prepare("select count(*) from freeblocks where cidr='$cidr'");
    $sth2->execute;
    @data = $sth2->fetchrow_array;
    if ($data[0] eq '1') {
      print "\t...but found in freeblocks.\n";
    } else {
      print "\t...and not found in freeblocks.\n";
    }
  }
  $i++;
}
