#!/usr/bin/env python

import json, urlparse, sys, os
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
from subprocess import call

class GitAutoDeploy(BaseHTTPRequestHandler):

	CONFIG_FILEPATH = './GitAutoDeploy.conf.json'
	config = None
	quiet = False
	daemon = False

	@classmethod
	def getConfig(myClass):
		if(myClass.config == None):
			try:
				configString = open(myClass.CONFIG_FILEPATH).read()
			except:
				sys.exit('Could not load ' + myClass.CONFIG_FILEPATH + ' file')

			try:
				myClass.config = json.loads(configString)
			except:
				sys.exit(myClass.CONFIG_FILEPATH + ' file is not valid json')

			for repository in myClass.config['repositories']:
				if(not os.path.isdir(repository['path'])):
					sys.exit('Directory ' + repository['path'] + ' not found')
				if(not os.path.isdir(repository['path'] + '/.git')):
					sys.exit('Directory ' + repository['path'] + ' is not a Git repository')

		return myClass.config

	def do_POST(self):
		urls = self.parseRequest()
		for url in urls:
			paths = self.getMatchingPaths(url)
			for path in paths:
				self.pull(path)
				self.deploy(path)
		self.respond()

	def parseRequest(self):
		length = int(self.headers.getheader('content-length'))
		body = self.rfile.read(length)
		post = urlparse.parse_qs(body)
		items = []

		# If payload is missing, we assume gitlab syntax.
		if not 'payload' in post and 'repository' in body:
			response = json.loads(body)
			items.append(response['repository']['url'])

		# Otherwise, we assume github syntax.
		else:
			for itemString in post['payload']:
				item = json.loads(itemString)
				items.append(item['repository']['url'])

		return items

	def getMatchingPaths(self, repoUrl):
		res = []
		config = self.getConfig()
		for repository in config['repositories']:
			if(repository['url'] == repoUrl):
				res.append(repository['path'])
		return res

	def respond(self):
		self.send_response(200)
		self.send_header('Content-type', 'text/plain')
		self.end_headers()

	def pull(self, path):
		if(not self.quiet):
			print "\nPost push request received"
			print 'Updating ' + path
		call(['cd "' + path + '" && git fetch origin && git update-index --refresh &> /dev/null && git reset --hard origin/master'], shell=True)

	def deploy(self, path):
		config = self.getConfig()
		for repository in config['repositories']:
			if(repository['path'] == path):
				if 'deploy' in repository:
					 if(not self.quiet):
						 print 'Executing deploy command'
					 call(['cd "' + path + '" && ' + repository['deploy']], shell=True)
				break

def main():
	try:
		server = None
		for arg in sys.argv:
			if(arg == '-d' or arg == '--daemon-mode'):
				GitAutoDeploy.daemon = True
				GitAutoDeploy.quiet = True
			if(arg == '-q' or arg == '--quiet'):
				GitAutoDeploy.quiet = True

		if(GitAutoDeploy.daemon):
			pid = os.fork()
			if(pid != 0):
				sys.exit()
			os.setsid()

		if(not GitAutoDeploy.quiet):
			print 'Github & Gitlab Autodeploy Service v 0.1 started'
		else:
			print 'Github & Gitlab Autodeploy Service v 0.1 started in daemon mode'

		server = HTTPServer(('', GitAutoDeploy.getConfig()['port']), GitAutoDeploy)
		server.serve_forever()
	except (KeyboardInterrupt, SystemExit) as e:
		if(e): # wtf, why is this creating a new line?
			print >> sys.stderr, e

		if(server is not None):
			server.socket.close()

		if(not GitAutoDeploy.quiet):
			print 'Goodbye'

if __name__ == '__main__':
	 main()

@@ -46,16 +46,24 @@
  sys, os
+, signal
 %0Afrom Ba
@@ -2565,27 +2565,36 @@
 ak%0A%0A
-def m
+%0Aclass GitAutoDeployM
 ain
-()
 :%0A%09
-try:%0A%09
+%0A
 %09ser
@@ -2603,16 +2603,33 @@
 r = None
+%0A%0A%09def run(self):
 %0A%09%09for a
@@ -2824,17 +2824,16 @@
  = True%0A
-%0A
 %09%09if(Git
@@ -3096,16 +3096,21 @@
 ode'%0A%0A%09%09
+self.
 server =
@@ -3179,16 +3179,21 @@
 ploy)%0A%09%09
+self.
 server.s
@@ -3211,135 +3211,105 @@
 r()%0A
-%09except (KeyboardInterrupt, SystemExit) as e:%0A%09%09if(e): # wtf, why is this creating a new line?%0A%09%09%09print %3E%3E sys.stderr, e
+%0A%09def close(self, signum, frame):%0A%09%09if(not GitAutoDeploy.quiet):%0A%09%09%09print '%5CnGoodbye'
 %0A%0A%09%09if(
+self.
 serv
@@ -3328,16 +3328,21 @@
 ne):%0A%09%09%09
+self.
 server.s
@@ -3359,92 +3359,173 @@
 e()%0A
-%0A
 %09%09
-if(not GitAutoDeploy.quiet):%0A%09%09%09print 'Goodbye'%0A%0Aif __name__ == '__main__':%0A%09 mai
+%09sys.exit()%0A%0Aif __name__ == '__main__':%0A%09gadm = GitAutoDeployMain()%0A%09%0A%09signal.signal(signal.SIGHUP, gadm.close)%0A%09signal.signal(signal.SIGINT, gadm.close)%0A%0A%09gadm.ru
 n()%0A

Implement signal handler for kill -HUP and more later