#!/usr/bin/env python
"""
Scrape a user's Videotron quota for the current period and report it.

FIXME TODO: automatically figure out the quota from the details on the page and
the current plan that is indicated.
"""
__author__ = 'Martin Blais <blais@furius.ca>'

import sys, re, smtplib
from StringIO import StringIO
from urllib import urlopen
from BeautifulSoup import BeautifulSoup
from decimal import Decimal


title = 'Videotron Quota Monitor'
url = ('https://www.videotron.com/'
       'services/secur/ConsommationInternet.do?compteInternet=%s')

limit_dl = Decimal('20')
limit_ul = Decimal('10')

def main():
    import optparse
    parser = optparse.OptionParser(__doc__.strip())
    opts, args = parser.parse_args()

    if len(args) != 1:
        parser.error("You need to supply your customer id.")
    userid, = args

    print url % userid
    soup = BeautifulSoup(urlopen(url % userid))
    table = soup.find('table', {'class': 'data'})
    tbody = table.find('tbody')
    tr = tbody.find('tr')

    td = soup.find('td', {'nowrap': 'nowrap'})
    assert td is not None
    period = td.renderContents()
    begin, end = re.findall('(\d\d\d\d-\d\d-\d\d)', period)

    tds = td.parent.findAll('td', {'align': 'right'})
    n_dl = tds[1]
    n_ul = tds[3]
    dl = Decimal(n_dl.string)
    ul = Decimal(n_ul.string)
    oss = StringIO()

    ## print >> oss, title
    for x in (("Period Begin", begin),
              ("Period End", end),
              ("Download", dl),
              ("Upload", ul)):
        print >> oss, '%-16s: %s' % x
    payload = oss.getvalue()
    print payload
    if dl > limit_dl or ul > limit_ul:
        print >> sys.stderr, "Videotron Quota over limit, sending email."
        smtpclient = smtplib.SMTP()
        smtpclient.connect('localhost')
        smtpclient.sendmail('Internet Bandwidth Watchdog <cron@furius.ca>',
                            'blais@furius.ca',
                            payload)
        smtpclient.quit()


if __name__ == '__main__':
    main()

