#!/usr/bin/env python

import httplib, mimetypes, sys

def post_multipart(host, uri, fields, files):
    content_type, body = encode_multipart_formdata(fields,files)
    h = httplib.HTTPConnection(host)
    h.putrequest('POST', uri)
    h.putheader('content-type', content_type)
    h.putheader('content-length', str(len(body)))
    h.endheaders()
    h.send(body)
    response = h.getresponse()
    return response.read()

def encode_multipart_formdata(fields, files):
    BOUNDARY = '----------ThIs_Is_tHe_bouNdaRY_$'
    CRLF = '\r\n'
    L = []
    for (key, value) in fields:
        L.append('--' + BOUNDARY)
        L.append('Content-Disposition: form-data; name="%s"' % key)
        L.append('')
        L.append(value)
    for (key, filename, value) in files:
        L.append('--' + BOUNDARY)
        L.append('Content-Disposition: form-data; name="%s"; filename="%s"' % (key, filename))
        L.append('Content-Type: %s' % get_content_type(filename))
        L.append('')
        L.append(value)
    L.append('--' + BOUNDARY + '--')
    L.append('')
    body = CRLF.join(L)
    content_type= 'multipart/form-data; boundary=%s' % BOUNDARY
    return content_type, body

def get_content_type(filename):
    return mimetypes.guess_type(filename)[0] or 'application/octet-stream'

upfile = 'popcon-data'
uploadname = 'popcondata'
val = sys.stdin.read()

data = ((uploadname,upfile,val),)
ret= post_multipart('popcon.ubuntu.com', '/popcon-submit.cgi', '' , data)
if not ret == 'Thanks!\n': 
    sys.stderr.write("%s\n" % ret)
    sys.exit(1)
