#!/usr/bin/python

import os, subprocess

def pull(branch, repo):
    p = subprocess.Popen("git pull", 
                         shell=True, 
                         stdout=subprocess.PIPE,
                         stderr=subprocess.STDOUT)

    (stdout, stderr) = p.communicate()
    stdout = "Executing \`git pull\` on branch '%s' ...\n\n %s" % (branch, stdout)
    
    cmd = "zwrite -d -c gutenbach-auto -i \"%s\" -s \"post-receive hook\" -O auto -m \"%s\"" % (repo, stdout)
    p = subprocess.Popen(cmd,
                         shell=True,
                         stdout=subprocess.PIPE,
                         stderr=subprocess.STDOUT)
    
    (stdout, stderr) = p.communicate()

def checkout(branch):
    p = subprocess.Popen("git checkout %s" % branch,
                         shell=True,
                         stdout=subprocess.PIPE,
                         stderr=subprocess.STDOUT)
    
    (stdout, stderr) = p.communicate()

def update(branch, repo):
    checkout(branch)
    pull(branch, repo)

def get_branches():
    p = subprocess.Popen("git branch | sed s/\ \ //g | sed s/*\ //g",
                         shell=True,
                         stdout=subprocess.PIPE,
                         stderr=subprocess.PIPE)
    (stdout, stderr) = p.communicate()

    branches = stdout.strip().split("\n")
    return branches
    
os.chdir("/afs/sipb.mit.edu/project/gutenbach/gutenbach")

# we should figure out something smart here to detect which branch was
# updated, instead of pulling all branches
for branch in get_branches():
    update(branch, "gutenbach")

checkout("master")
