#!/usr/bin/env python

import collections
import sys
import urllib2
import json

MIBZ_URL = "http://mibz.org/by-node/%s" % (sys.argv[1])
MIBS_DIR = "/usr/share/mibs/"

def fetch_it(url):
	mib = urllib2.urlopen(url)
	filepath = "%s%s" % (MIBS_DIR, mib.geturl().split("/")[-1])
	try:
		with open(filepath, 'w') as f:
			f.write(mib.read())
	except IOError, e:
		print "Looks like you don't have a standard /usr/share/mibs folder(!)"
		print "Try >apt-get install snmp\n Failing."
		sys.exit(1)

mib_list = json.loads(urllib2.urlopen(MIBZ_URL).read(), object_pairs_hook=collections.OrderedDict)
if not mib_list:
	print "Term not found on mibz.org."
	sys.exit(0)
	
for mib_name in mib_list.keys():
	fetch_it(mib_list[mib_name])
	print "%s (from %s)..." % (mib_name, mib_list[mib_name])
print "\n Use this term as %s::%s" % (mib_list.keys()[0], sys.argv[1])
