#!/usr/bin/env python
import cgi, cgitb
import json, re
import logging
import os, shutil
cgitb.enable()

DIR = '/tmp/'

print "Content-Type: text/html"     # HTML is following
print                               # blank line, end of headers

logger = logging.getLogger('post-receive')
logger.setLevel(logging.INFO)
handler = logging.handlers.SysLogHandler(address="/dev/log")
logger.addHandler(handler)

try:
  form = cgi.FieldStorage()
  payload = form.getvalue("payload")
  if payload is None:
    exit(0)

  logger.info(payload)
  payload = json.loads(payload)

  ref = payload['ref']
  if re.match("^refs\/tags\/", ref) is not None:
    #it is a tag
    logger.info("received tag")
    # run deploy - 
    #   git clone $payload['repository']['url']
    #   git checkout $ref
    os.system('git clone %s %s/%s' % (payload['repository']['url'], DIR, payload['repository']['name']))

    cwd = os.getcwd()

    os.chdir('%s/%s' % (DIR, payload['repository']['name']))
    os.system('git checkout %s' % payload['ref'])
    os.system('make install')

    gitdir = os.getcwd()
    os.chdir(cwd)
    shutil.rmtree(gitdir)
except Exception as e:
  logger.error(e)
