"""
Simple script to post stuff to cmlenz' scratchpad

2008-04-06 Tim Hatch <code@timhatch.com>
"""

import urllib2
import urllib

import re
import sys

R_TOKEN = re.compile(r'name="__token__" value="([0-9a-z]+)')

BASEURL = "http://scratchpad.cmlenz.net/post/"

def main(filename, mimetype='text/plain'):
    file_data = open(filename, 'rb').read()
    
    first_page = urllib2.urlopen(BASEURL)
    token_match = R_TOKEN.search(first_page.read())
    if not token_match:
        print "Cannot find token in post page"
        return -1
    token = token_match.group(1)
    #print "Token is", token

    postdata = urllib.urlencode({'title': filename,
                                 'mimetype': mimetype,
                                 'content': file_data,
                                 '__token__': token})
    req = urllib2.Request(BASEURL, postdata)
    req.add_header('Referer', BASEURL)
    req.add_header('Cookie', 'form_token=%s' % token)

    second_page = urllib2.urlopen(req)
    print second_page.url

if __name__ == '__main__':
    sys.exit(main(*sys.argv[1:]))

