#!/usr/bin/env python

import timeit
import subprocess
import os
import StringIO
import json
import urllib
import time
import sys, daemon #python daemon is an external library and needs to be installed


class ChangDir:
	def __init__(self, path):
		self.currentPath = os.getcwd() #returns current working directory
		os.chdir(path)
	#return to the original directory
	def __del__(self):
		os.chdir(self.currentPath)

def checkCommitsAndUpdate(gitpath, phpserverpath, branch="master"):
    dirchanger = ChangDir(gitpath)

    output = subprocess.check_output(["git", "log","-1"])
    
    buf = StringIO.StringIO(output)

    commit_local = buf.readline()

    if("commit" in commit_local):
    	commit_local = str(commit_local.split(" ")[1]).strip()
    	print commit_local
    	
    	#retrieve the last push from github
    	f = urllib.urlopen(phpserverpath)
    	jsonObj = json.loads(f.read())
    	commit_remote = str(jsonObj['commits'][0]['id']).strip()
    	
        print commit_remote

    	if commit_remote != commit_local:
    		output = subprocess.check_output(["git", "pull","origin", branch])
    		print output
    	else:
    		print "Already up-to-date"

def main(argv):
    gitapth =''
    phpserverpath=''

    if len(argv) != 3:
        print "Usage: numi.py <git local repo path> <php server path> [branch(optional)]"
        print ""
    else:
        gitpath = argv[1]
        phpserverpath = argv[2]

        while True:
            if len(argv) == 4:
                checkCommitsAndUpdate(gitpath, phpserverpath, argv[3])
            else:
                checkCommitsAndUpdate(gitpath, phpserverpath)
            time.sleep(30)

if __name__ == "__main__":
    #with daemon.DaemonContext():
    main(sys.argv)





