#!/usr/bin/perl

&make_arin;
&make_nic("RIPE", "ftp://ftp.ripe.net/ripe/dbase/split/ripe.db.aut-num.gz", "as-ripe.txt");
&make_nic("APNIC", "ftp://ftp.apnic.net/pub/whois-data/APNIC/split/apnic.db.aut-num.gz", "as-apnic.txt");
&make_nic("JPNIC", "ftp://ftp.apnic.net/pub/whois-data/JPNIC/split/jpnic.db.aut-num.gz", "as-jpnic.txt");
&make_lacnic;

sub make_arin() {

	open (F1, "wget -q -O - ftp://ftp.arin.net/netinfo/asn.txt |");
	open (F2, "> as-arin.txt");

	print F2 <<EOT;
#
# This file is generated automatically from
# ftp://ftp.arin.net/netinfo/asn.txt
#
# Do not edit this file
#
EOT

	while (<F1>) {
		chop;
		next if (/ APNIC-AS-\d+-BLOCK /);
		next if (/ RIPE-ASNBLOCK\d+ /);
		next if (/ ASNBLK-RIPE /);
		next if (/ ASNBLK-RIPE-NCC /);
		next if (/ ASN-BLKRIPE\d+ /);
		if (/^  ([\d\-]+)\s+(\S+)\s/) {
			my $autnum = $1;
			my $descr = $2;
			if ($autnum =~ /^(\d+)-(\d+)$/) {
				for (my $i = $1; $i <= $2; $i++) {
					printf(F2 "%5d\tARIN:%s\n", $i, $descr);
				}
			} else {
				printf(F2 "%5d\tARIN:%s\n", $autnum, $descr);
			}
		} else {
			next;
		}
	}

	close F2;
	close F1;
}

sub make_nic() {
	my ($nicprefix, $url, $filename) = @_;

	open (F1, "wget -q -O - $url | gunzip |");

	my $autnum = "";
	my $descr;

	my @asnums;

	while (<F1>) {
		chop;
		if (/^aut-num:\s+[Aa][Ss](\d+)$/) {
			$autnum = $1;
			next;
		} elsif (/^as-name:\s+(.*)$/) {
			next if ($1 eq "UNSPECIFIED");
			$descr = $1;
		} elsif (/^descr:\s+(.*\w.*)$/) {
			next if ($autnum eq "");
			$descr = $1;
		} else {
			next;
		}

		if ($autnum ne "") {
			$asnum[$autnum] = $descr;
			$autnum = "";
			$descr = "";
		} else {
			print STDERR "missing aut-num for as-name [$1] in line $.\n";
		}
	}

	close F1;

	open (F2, "> $filename");

	print F2 <<EOT;
#
# This file is generated automatically from
# $url
#
# Do not edit this file
#
EOT

	for (my $i = 1; $i < 65536; $i++) {
		printf(F2 "%5d\t${nicprefix}:%s\n", $i, $asnum[$i]) if ($asnum[$i] ne "");
	}

	close F2;
}

sub make_lacnic() {

	open (F1, "wget -q -O - ftp://whois.lacnic.net/pub/stats/lacnic/delegated-lacnic-latest |");
	open (F2, "> as-lacnic.txt");

	print F2 <<EOT;
#
# This file is generated automatically from
# ftp://whois.lacnic.net/pub/stats/lacnic/delegated-lacnic-latest
#
# Do not edit this file
#
EOT

	while (<F1>) {
		chop;
		if (/^lacnic\|([A-Z][A-Z])\|asn\|(\d+)\|/) {
			printf(F2 "%5d\tLACNIC:%s\n", $2, $1);
		}
	}

	close F2;
	close F1;
}

