#!/usr/bin/env python

############################################################################
#    Copyright (C) 2007 by Jussi Pakkanen and the Nouveau team             #
#    http://nouveau.freedesktop.org/wiki/                                  #
#                                                                          #
#    This program is free software; you can redistribute it and/or modify  #
#    it under the terms of the GNU General Public License as published by  #
#    the Free Software Foundation; either version 2 of the License, or     #
#    (at your option) any later version.                                   #
#                                                                          #
#    This program is distributed in the hope that it will be useful,       #
#    but WITHOUT ANY WARRANTY; without even the implied warranty of        #
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         #
#    GNU General Public License for more details.                          #
#                                                                          #
#    You should have received a copy of the GNU General Public License     #
#    along with this program; if not, write to the                         #
#    Free Software Foundation, Inc.,                                       #
#    59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             #
############################################################################

import os, urllib, sys

nvidia_id = '10de'


# Needs to support the following formats:
#
# 00:00.0 0580: 10de:005e (rev a3)
#
# 00:18.0 0600: 1022:1100
#
# 01:00.0 Class 0300: 1002:4c57
#
# 00:00.0 Class 0600: 8086:1a30 (rev 04)

def get_system_pci_data(vendor_id):
	lines = os.popen('lspci -n').readlines()
	lines = map(lambda x: x.split(':', 2)[-1], lines)
	lines = map(lambda x: x.split()[0], lines)
	lines = filter(lambda x: x.startswith(nvidia_id), lines)
	lines = map(lambda x: x.split(':')[1], lines)
	return lines

def parse_card_info(line):
	state = line.split('"')[1]
	pciid = line.split('>')[2][0:4]
	return (pciid, state)

def build_db(d, pciid):
	d[pciid[0]] = pciid[1]
	return d

def print_db_lines(db, item):
	if db.has_key(item):
		print item, db[item]
	return db

def get_dump_status(url):
	if url.startswith('http://'):
		stext = urllib.urlopen(url).readlines()
	else:
		stext = file(url, 'r').readlines()
	clines = filter(lambda x: x.startswith("<tr class="), stext)
	clines = map(parse_card_info, clines)
	cdict = reduce(build_db, clines, {})
	return cdict

def print_system_info(db, pciids):
	print 'ID   Status'
	reduce(print_db_lines, pciids, db)

if __name__ == '__main__':
	if len(sys.argv) != 2:
		print "This script tells the dump state of NVidia graphic card(s) on your system.\n"
		print sys.argv[0], '<http address of dump status page>'
		sys.exit(1)
	pciids = get_system_pci_data(nvidia_id)
	db = get_dump_status(sys.argv[1])
	print_system_info(db, pciids)
