#!/bin/bash

if [ $# -eq 0 ]; then
    echo "usage: get_internet2_netblocks <output_filename>" >&2
    exit 1
fi

outfile="$1"
tmpdir=$(mktemp -d /tmp/get_i2_netblocks.XXXXXXXX) || exit 1
trap "rm -rf ${tmpdir}" EXIT QUIT HUP KILL TERM
listfile=$tmpdir/list

function last_rib()
{
	tail ${tmpdir}/index.html | grep rib\. | tail -n 1 | \
	awk -F 'href="' '{print $2}' | \
	sed -e 's/".*//'
}

function get_i2_netblocks()
{
    URL='http://syslog.abilene.ucaid.edu/bgp/WASH/RIBS'
    wget -q -O ${tmpdir}/index.html "${URL}/"
    last=$(last_rib)
    wget -O ${tmpdir}/rib.gz -q "${URL}/$last"
    zcat ${tmpdir}/rib.gz | perl internet2/zebra-dump-parser/zebra-dump-parser.pl > ${listfile}
}

get_i2_netblocks
if [ -s ${listfile} ]; then
    cp -f ${listfile} "${outfile}"
else
    echo "unable to retrieve netblock list." >&2
    exit 1
fi
exit 0
