#!/usr/bin/ruby -w


`curl -s ftp://ftp.ripe.net/ripe/dbase/split/ripe.db.route.gz  | gunzip - > /tmp/ripe.db.route`
`curl -s ftp://ftp.arin.net/pub/originAS/originAS_arin-latest.txt -o /tmp/originAS_arin-latest.txt`
`curl -s ftp://ftp.apnic.net/pub/apnic/whois-data/RADB/split/radb.db.route.gz | gunzip - > /tmp/radb.db.route`

outputfile = "AS-list.txt"

class ASparser 

    def parse(file)

	fh = File.open(file)
	routes = {}
	route = nil

	line_num = 1
	fh.each_line { |l|
	    if l =~ /^route:\s+(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\/\d{1,2})/
		route = $1
	    end
	    if l =~ /^origin:\s+AS(\d+)$/
		$stderr.puts "DEBUG: AS: #{$1} but prefix is not set - line_num = #{line_num} of file #{file}" if route.nil?
		routes[route] = $1 unless route.nil?
		route = nil
	    end
	    line_num += 1
	}
	return routes
    end

    def originparse(file)
	fh = File.open(file)

	routes = {}
	fh.each_line { |l|
	    if l =~ /(\d+\.\d+\.\d+\.\d+\/\d+)\|AS(\d+)\|/
		routes[$1] = $2 
	    end
	}
	return routes
    end
end

parser = ASparser.new


ripe = parser.parse("/tmp/ripe.db.route")
radb = parser.parse("/tmp/radb.db.route")
arin = parser.originparse("/tmp/originAS_arin-latest.txt")

all_routes = radb.merge(arin)
all_routes.merge!(ripe)
all_routes.rehash

as_list = File.new(outputfile, "w+")
all_routes.each {|k,v|
    as_list.puts "#{v}:#{k}"
}
