#!/usr/bin/python

# Written by Bertrand Grelot
# requires python-beautifulsoup

import os
import re
import sys
import urllib

from BeautifulSoup import BeautifulSoup

url = 'http://fah-web.stanford.edu/cgi-bin/main.py?qtype=osstats'

code = os.environ.get('code', sys.argv[0][(sys.argv[0].rfind('_') + 1):])

if code == None: sys.exit(1)

if len(sys.argv) == 2 and sys.argv[1] == "autoconf":
        print "yes"
elif len(sys.argv) == 2 and sys.argv[1] == "config":
        print 'graph_title Active CPU in FoldingAtHome project'
        print 'graph_vlabel Systems'
        print 'graph_category htc'

        print 'windows.label Windows'
        print 'ppc.label MacOS/PowerPC'
        print 'intel.label MacOS/Intel'
        print 'linux.label Linux'
        print 'ati.label ATI_gpu'
        print 'nvidia.label NVIDIA_gpu'
        print 'ps3.label Playstation3'

        print 'graph_args --base 1000 -l 0'
else:
        u = urllib.urlopen(url)
        soup = BeautifulSoup(u)
        u.close()

        l=[]
        i=0

        table = soup.find('table')
        rows = table.findAll('tr', bgcolor="#f5f5dc")

        for tr in rows:
                cols = tr.findAll('td')
                l.append([])
                for td in cols:
                        l[i].append(td.find(text=True))
                i+=1

        WIN=l[0][3]
        MPPC=l[1][3]
        MINTEL=l[2][3]
        LINUX=l[3][3]
        ATI=l[4][3]
        NVIDIA=l[5][3]
        PS3=l[6][3]

        print 'windows.value %s' % WIN
        print 'ppc.value %s' % MPPC
        print 'intel.value %s' % MINTEL
        print 'linux.value %s' % LINUX
        print 'ati.value %s' % ATI
        print 'nvidia.value %s' % NVIDIA
        print 'ps3.value %s' % PS3

