#!/usr/bin/env python

from BeautifulSoup import BeautifulSoup
import urllib2
import os

# URL for Jandakot airport last few days obs.
URL = "http://www.bom.gov.au/products/IDW60801/IDW60801.94609.shtml"
FLAGFILE = "/home/daniel/sprinklers/enough-rain"

try:
	os.unlink(FLAGFILE)
except OSError:
	# File not found... ignore...
	pass

page = urllib2.urlopen(URL)
soup = BeautifulSoup(page)

totalrain = 0.0
steprain  = 0.0

# For each table with data in it.
tables = soup.findAll('table', attrs={'class': "tabledata"})
tables.reverse()
for table in tables:
	rows = table.findAll('tr', attrs={'class': "rowleftcolumn"})
	rows.reverse()
	for row in rows:
		cell = row.findChildren()[13]
		try:
			rain = float(cell.contents[0])
		except ValueError, e:
			# Hmm... invalid input.
			rain = steprain
		if rain > steprain:
			steprain = rain
		if rain < steprain:
			totalrain += steprain
			steprain = 0.0

# And now we have the rain for the last few days.
# More than 5mm? Set our "too much rain" flag.
if totalrain >= 5.0:
	f = open(FLAGFILE, 'w')
	f.write(str(totalrain))
	f.close()

