#!/usr/bin/python
# download latest Intel processor microcode
# (c) 2010: Daniel J Blueman, Stefano Rivera
# GPL v3 license [http://fsf.org/]

import json
import os
from StringIO import StringIO
import sys
import tarfile
import urllib2

url = 'http://downloadcenter.intel.com/JSONDataProvider.aspx?OSVersion=Linux*&DownloadType=Firmware&ProductFamily=Processors&ProductLine=Desktop&ProductProduct=Intel%C2%AE%20Core%E2%84%A2%20i7%20Desktop%20Processor&sortDir=descending&refresh=filters&dataType=json&type=GET'

try:
	data = urllib2.urlopen(url).read()
except urllib2.HTTPError, e:
	print 'failed to download microcode index - %s' % e.code
	sys.exit(1)
except urllib2.URLError, e:
	print 'failed to download microcode index - %s' % e.reason
	sys.exit(1)

results = json.loads(data)['results']
assert len(results), "no search results - microcode search URL needs updating"

# check for numerically highest date
newest = sorted(results, key=lambda x: x['version'])[-1]

srcurl = 'http://downloadmirror.intel.com/%s/eng/microcode-%s.tgz' % (newest['title']['downloadid'], newest['version'])

try:
	src = urllib2.urlopen(srcurl)
except urllib2.HTTPError, e:
	print 'failed to download microcode from %s - %s' % (srcurl, e.code)
	sys.exit(1)
except urllib2.URLError, e:
	print 'failed to download microcode from %s - %s' % (srcurl, e.reason)
	sys.exit(1)

tar = tarfile.open(mode='r:gz', fileobj=StringIO(src.read()))
src = tar.extractfile('microcode.dat')
dstpath = '/usr/share/misc/intel-microcode.dat'

try:
	dst = file(dstpath, 'w')
	dst.write(src.read())
	dst.close()
	os.chown(dstpath, 0, 0)
except OSError, e:
	print 'failed to install microcode to %s - %s' % (dstpath, e.strerror)
	sys.exit(1)

print 'successfully downloaded Intel %s microcode' % newest['version']
