#!/usr/local/bin/python
import anydbm,cgi,os; db=anydbm.open('/tmp/short_db','c')
form = cgi.FieldStorage()
if form.getfirst('url','') and len(db) >= 10000: print 'content-type: text/html\r\n\r\nDB Full'
elif form.getfirst('url',''):
    id = unichr(len(db)+1+100).encode('utf-16be').encode('base64').strip().rstrip('='); db[id] = form.getfirst('url','')[:4096]
    print 'content-type: text/html\r\n\r\n<html><body><a href="http://tungwaiyip.info/shorturl/%s">http://tungwaiyip.info/shorturl/%s</a></body></html>' % (id,id)
elif os.environ.get('PATH_INFO','')[:50].lstrip('/'): print 'status: 302 found\r\nlocation: %s\r\n\r\n' % (db.get(os.environ.get('PATH_INFO','')[:50].lstrip('/'),'.'))
else: print 'content-type: text/html\r\n\r\n<html><head><title>The World\'s Shortest Short URL Generator</title><link title="Main Style" rel="stylesheet" href="/main.css" type="text/css"></head><body><h1>The World\'s Shortest Short URL Generator</h1><p>Please enter full URL:</p><form method="get" action="/shorturl">URL <input name="url" type="text" value="http://" size="80" /><input value="Shorten" type="submit" /></form><p style="margin-top:8ex"><a href="http://tungwaiyip.info/blog/2009/05/12/the_worlds_shortest_short_url_generator">About</a>&nbsp;&nbsp;<a href="http://tungwaiyip.info/software/shorturl/short.py">Source Code</a></p><p><small>Disclaimer: This site is built for fun only. Short URLs generated are only going to be valid for a short period of time.</small></p></body></html>'
db.close()
