#!/bin/sh
#set -vx

# This script generates the SQL statements needed to populate the SellaNMS
# database with information about BGP ASNs ().
#
# Since this script gets its information via whois, it will run run for
# hours to complete.

# You can also build part of the data using ARINs asn.txt from ftp://ftp.arin.net/info/asn.txt
# awk '{ if ($1 ~ /[0-9][0-9]*/ && $1 !~ /-/) printf("INSERT INTO asn VALUES (\"%s\", \"%s\",\"\",\"\");\n", $1, $2); }' asn.txt | mysql -u sella_nms -p sella_nms

ASN=1
LIMIT=60000

printf "DELETE FROM asn;\nLOCK TABLE asn WRITE;\n"

while [ ${ASN} -lt ${LIMIT} ]; do
	wget "http://ws.arin.net/whois/?queryinput=${ASN}" -q -O - | sed 's/:  */:/' | sed 's/  *$//' | sed 's/"/\\"/g' | awk -F':' '{ if (/^ASNumber:/) as=$2; if (/^OrgName:/) org=$2; if (/Phone:/) phone=$2; if (/TechEmail:/) { email=$2; exit; } if (/NOCEmail:/) { email=$2; exit; } } END { if (as ~ /^[0-9]+$/) printf("INSERT INTO asn_data (asn, name, email, phone) VALUES (\"%s\", \"%s\", \"%s\", \"%s\");\n", as, org, email, phone); }'

#	whois -h whois.arin.net ${ASN} | sed 's/:  */:/' | sed 's/  *$//' | awk -F':' '{ if (/^ASNumber:/) as=$2; if (/^OrgName:/) org=$2; if (/Phone:/) phone=$2; if (/TechEmail:/) { email=$2; exit; } if (/NOCEmail:/) { email=$2; exit; } } END { printf("INSERT INTO asn (asn, name, email, phone) VALUES (\"%s\", \"%s\", \"%s\", \"%s\");\n", as, org, email, phone); }'
	let ASN="${ASN} + 1"
done

printf "UNLOCK TABLES;\n"
