#!/usr/local/bin/python

import cgi
import os
import sys
import urllib

form = cgi.FieldStorage()

is_cgi = 'SERVER_NAME' in os.environ

if is_cgi:
  url = form["url"].value
else:
  url = "http://www.evilgeniuschronicles.org/wordpress/feed/atom/"  

url_file = urllib.urlopen(url)

for header in url_file.info().headers:
  # We're changing the length of the content, so don't reuse the
  # existing one
  if header.lower().find("content-length:") == 0: continue
  
  # Force text/xml as the content-type, since some sites use text/html even for 
  # feeds, and when they use application/atom+xml Firefox will ignore the 512
  # byte header hack and we always want to force Firefoxto render this as XML
  if header.lower().find("content-type:") == 0:
    sys.stdout.write("Content-Type: text/xml\n")
    continue
  
  sys.stdout.write(header)

sys.stdout.write("\n")

feed_data = url_file.read()

padding = " " * 512 + "\n"

feed_start = feed_data.find("<feed")
if feed_start == -1:
  feed_start = feed_data.find("<rss")

if feed_start != -1:
  feed_data = \
      '<?xml version="1.0" encoding="UTF-8"?>' + \
      padding + \
      feed_data[feed_start:]

sys.stdout.write(feed_data)

url_file.close()