#!/usr/bin/python

"""
cgi-bin/packawhallop/calendar.py

"""

import os
import sys
import commands
import re
import time

# Function to check whether a value is in fact a number. int() won't do it on 
# its own. 
def isnum(x):	
	if x.strip() == '': 
		return False
	else: 
		try: 
			eval(x+'0') 
			return True
		except: 
			return False

# Set HTTP path to application. This will be used to map to CSS and JavaScript.
http_root = "http://www.salt.edu"
# Initialize page. This is where we'll draw our calendar's markup before 
# dispatching it to the web page. 
page = ''
# To make nicely formatted markup easily readable when viewing source through 
# the web browser use 'grokable = True' here. Otherwise to not bother with tabs
# and carriage returns and just draw the markup in what's sometimes called a 
# compressed manner use 'grokable = False' here instead. 
grokable = True
# Initialize associative array (in Python associative arrays are called 
# dictionaries) to hold querystring variables. 
get = {"f" : "", "m" : "", "y" : "", "o" : ""}
# On UNIX systems cal is the program that'll draw a calendar. On Mac OS X (for
# example) start Terminal (Terminal.app) and type 'cal' and press RETURN. You 
# will get a little calendar-ish calendar. Neat huh? Welcome to UNIX-land! So 
# cal gives us a calendar without our needing to go through the tedium of 
# contructing one in Python. Which we could do... but why when we just have to
# parse output from cal? Naturally we need cal on the system to be able to use 
# it. 
calbin = "/usr/bin/cal"
if os.path.exists(calbin) and os.path.isfile(calbin) and os.access(calbin, os.X_OK): 
	# Two valid querystring arguments: 'y' for year and 'm' for month, gotten 
	# from the environment variables, with some checking to make certain that the
	# values are sane. 
	if os.environ['QUERY_STRING'] <> '': 
		qs = os.environ['QUERY_STRING'].strip().split("&")
		if len(qs) > 0: 
			for vars in qs: 
				var, val = vars.split("=")
				if re.search("^(f|m|y|o)$", var): 
					get[var]= val
	if not isnum(get['m']) or int(get['m']) < 1 or int(get['m']) > 12: 
		get['m'] = time.localtime()[1]
		get['y'] = time.localtime()[0]
	if isnum(get['o']): 
		ts = time.mktime((int(get['y']), int(get['m']) + int(get['o']), 1, 0, 0, 0, 0, 0, -1))
		get['m'] = time.localtime(ts)[1]
		get['y'] = time.localtime(ts)[0]		
	grid = commands.getstatusoutput(calbin +" "+ str(get['m']) +" "+ str(get['y']))[1]
	if grid.strip() <> '': 
		rows = grid.split("\n")
		if len(rows) > 0: 
			page += '<div id="calendar">'+"\n\t"+'<div class="grid">'
			for rowno in range(0, len(rows)): 
				if rows[rowno].strip() <> '': 
					page += "\n\t\t"+'<div class="'
					if rowno == 0: 
						page += 'month_year_'
					elif rowno == 1: 
						page += 'day_name_'
					else:
						page += ''
					page += 'row">'
					cells = re.split("\s+", rows[rowno].strip())
					if len(cells) > 0: 
						pat = re.compile("(JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)", re.IGNORECASE)
						if re.match(pat, cells[0]):
							page += "\n\t\t\t"+'<div class="tool_cell"><a href="?f='+ get['f'] +'&m='+ str(get['m']) +'&y='+ str(get['y']) +'&o=-1">&lt;&lt;</a></div>'
						if rowno == 0: 
							page += "\n\t\t\t"+'<div class="cell" style="width: 120px;">'+ cells[0] +' '+ cells[1] +'</div>'
						else: 
							if rowno == 2: 
								if 7 - len(cells) > 0: 
									for i in range(0, 7 - len(cells)): 
										page += "\n\t\t\t"+'<div class="filler_cell">&nbsp;</div>'
							for cell in cells: 
								if rowno == 1: 
									page += "\n\t\t\t"+'<div class="cell">'+ cell +'</div>'
								else: 
									if get['f'] <> '': 
										page += "\n\t\t\t"+'<div class="cell"><a href="#" onclick="javascript:setDate(\''+ get['f'] +'\',\''+ str(get['y']) +'-'+ str(get['m']) +'-'+ cell +'\');return false;">'+ cell +'</a></div>'
									else: 
										page += "\n\t\t\t"+'<div class="cell">'+ cell +'</div>'
						if re.match(pat, cells[0]): 
							page += "\n\t\t\t"+'<div class="tool_cell" style="float: right;"><a href="?f='+ get['f'] +'&m='+ str(get['m']) +'&y='+ str(get['y']) +'&o=1">&gt;&gt;</a></div>'
					page += "\n\t\t"+'</div>'
			page += "\n\t\t"+'<div class="row" style="clear:left">'+"\n\t\t\t"+'<div class="footer" style="width:100%;text-align:center"><a href="javascript:window.close();">Close</a></div>'+"\n\t\t".'</div>'+"\n";
			page += "\n\t"+'</div>'+"\n"+'</div>'+"\n"
			# Rip out tabs, carriage returns and newline characters if we're not 
			# concerned about making easy to read markup. 
			if grokable == False: 
				page = re.sub("\t|\r|\n", "", page)
		else: 
			page = '<em>Whoops. Something went wrong trying to fetch the calendar.</em>'
else: 
	page = '<em>Whoops. Can\'t draw a calendar. Reason: `cal` doesn\'t exist at `'+ calbin +'`. Maybe you need to open a shell and run `whereis cal`?</em>'
print "Content-type: text/html"
print 
print """
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
	<meta http-equiv="content-type" content="text/html; charset=utf-8" />
	<title></title>
<style type="text/css" title="text/css" media="screen">
/* <![CDATA[ */
@import url('%s/css/packawhallop/calendar.css');
/* ]]> */
</style>
<script type="text/javascript" language="javascript" charset="utf-8" src="%s/js/packawhallop/calendar.js"></script>
</head>
<body>
%s
</body>
</html>
""" % (http_root, http_root, page)
sys.exit()
