#!/bin/python
#
# Uncurl 0.3 
# 
# Converts cut/paste copy-as-curl from browser develpoer tools (and possibly
# other sources) into a short python program that does the same thing.
# 
# (C) Patrik Lundin 2015,
# You are hereby granted licence to reuse this code, with or without
# modification, with or without attribution, in any context or project you 
# wish, commercial or non-commercial, FOSS-licenced or closed-sourced.
# 
# If you to reuse ig, I'd apprechiate knowing about it (though it's by no means
# required). I can be contacted at patrik@nothisispatrik.com for that, or if 
# you have questions or comments in general.

import re
from sys import argv

if len(argv)==1:
    fn = '/dev/clipboard'
else:
    fn = argv[1]

ind = " "*4

pg = open(fn).read().replace('"%"','%')

if not pg.startswith("curl "):
    print "Invalid curl command (doesn't start with curl)"
    quit()
sofar = "import urllib3\nurllib3.disable_warnings()\n\ndef getpage():\n"

ec = pg.find(' ',5)

sofar +=  ind+"url = " + pg[5:ec] + "\n\n"
hs = pg[ec:]

if hs.startswith(' -x'):
    if hs[3] == ' ':
        x = 1
    else:
        x = 0
    xe = hs.find(' ',3+x)
    px = hs[3+x:xe]
    hs = hs[xe:]
else:   
    px = ""

if not hs.startswith(' -H '):
    print "Invalid curl command (first parameter after url isn't a header)"

hls = hs.split(' -H ')
if not hls[0]:
    hls = hls[1:]
eh = hls[-1].find('"',1)+1
res = hls[-1][eh:]
hls = hls[:-1] + [hls[-1][:eh]]

hls = map(lambda a:a.replace(": ",'": "'),hls)
sofar += ind + "he = {\n" + ind + ind + (',\n'+ind+ind).join(hls) + "\n" + ind + "}\n\n" 

if res.startswith(" --data "):
    data = res[8:]
    de = data.find('"',1)
    res = data[de+1:]
    data = data[:de+1]
    sofar += ind + "data = " + data + "\n\n"
else:
    data = ""

if not px:
    sofar += ind + "po = urllib3.PoolManager()\n"
else:
    sofar += ind + "po = urllib3.ProxyManager(http://"+px+")\n"

if not data:
    sofar += ind + "r = po.urlopen('GET', url, headers=he)\n"
else:
    sofar += ind + "r = po.urlopen('POST', url, headers=he, body=data)\n"

sofar += ind + "print '\\n'.join(map(': '.join,r.headers.items()))+'\\n'\n"
sofar += ind + "print r.data\n"
sofar += "\n\nif __name__==\"__main__\":\n"+ind+"getpage()"
print sofar

