#!/usr/bin/env python
# coding=UTF-8

# pastebin.py
# writes the input string to pastebin.com and returns the URL
#
# Copyright 2007-2012 Friedrich Preuß <info@phriedrich.de>
# all rights reserved, released under the terms of GPLv2

import sys
import urllib.request, urllib.parse, urllib.error
import re
from getpass import getuser

# own error handling class
class MyHTTPRedirectHandler(urllib.request.HTTPRedirectHandler):
	def http_error_302(self, req, fp, code, msg, headers):
		return(headers['location'])

	http_error_301 = http_error_303 = http_error_307 = http_error_302


class pastebin:
	def __init__(self):
		self.name = getuser()
		self.expiry = "1D"
		self.formatTable = {
				'Bash' : 8,
				'C' : 9,
				'C++' : 13,
				'CSS' : 16,
				'HTML' : 25,
				'Java' : 27,
				'JavaScript' : 28,
				'Lua' : 30,
				'None' : 1,
				'Perl' : 40,
				'PHP' : 41,
				'Python' : 42,
				'Rails' : 67
				}
	
	def determineCode(self, code):
		p = re.compile("#!/usr/bin/env python")
		if p.search(code):
			return(42)

		return 8
		
	def send(self, code):
		try:
			format = self.formatTable[self.format.title()]
		except:
			format = self.determineCode(code)

		url = 'http://pastebin.com/post.php'
		values = {'paste_form' : '/post.php',
				'submit_hidden' : 'submit_hidden',
				'paste_parent_key': '',
				'paste_subdomain' : '',
				'paste_code' : code,
				'paste_format' : format,
				'paste_expire_date' : self.expiry.upper(),
				'paste_private' : '0',
				'paste_name' : self.name,
				'paste_email' : '',
				'submit' : 'submit'}
		data = urllib.parse.urlencode(values).encode('UTF-8')

		opener = urllib.request.build_opener(MyHTTPRedirectHandler)
		urllib.request.install_opener(opener)
		
		response = urllib.request.urlopen(url, data)
		try:
			new_url = response.geturl()
			response.close()
		except:
			new_url = 'http://pastebin.com' + response

		return(new_url)

if __name__ == "__main__":
	paste = pastebin()
	for arg in sys.argv:
		if arg in ("-h", "--help"): 
			print("Usage: STDOUT | pastebin.py [--name=USERNAME] [--format=FORMAT] [--expiry=(N|10M|1H|1D|1M)]")
			sys.exit()  
		if ("--name") in arg:
			paste.name = arg.split('=')[1]
		if ("--format") in arg:
			paste.format = arg.split('=')[1]
		if ("--expiry") in arg:
			paste.expiry = arg.split('=')[1]

	code = sys.stdin.buffer.read().decode(sys.stdout.encoding)

	if code == '':
		print("No input data to send …")
		sys.exit()
			
	ret_url = paste.send(code)
	print(ret_url)


