#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys, os, time
from subprocess import *

modules = sys.argv[1:]


def isDirty(path):
    cmd = "cd %s && git diff |wc -l" % path
    p1 = Popen([cmd], shell=True, stdout=PIPE)
    #print p1.readlines()
    output = p1.communicate()[0]
    #print output
    #print path, "isDirty?", int(output) > 0
    return int(output) > 0

def isGitSvn(path):
    cmd = "cd %s && git svn info  > /dev/null 2>&1" % path
    retcode = call(cmd, shell=True)
    #print path, "is git-svn?", retcode == 0
    return retcode == 0
    #return False

srcpath = os.environ["KDE_SRC"]

if not srcpath.endswith('/'):
    srcpath = srcpath + '/'

if not os.path.isdir(srcpath):
    print "Source path %s does not exist, exiting" % srcpath
    os.exit(1)
    #"/home/sebas/kdesvn/src/"

#print "Source path %s does not exist, exiting" % srcpath
time.sleep(.2)

dirty = []
othererror = []

if len(modules) == 0:
    print "all modules in dir"
    modules = os.listdir(srcpath)

print "modules:", modules

for p in modules:
    path = srcpath + p
    #print path
    fullcmd = ""
    # Git or SVN?
    
    cmd = ""
    if os.path.isdir(path + "/.git/"):
        # git-svn or pure git?
        #cmd = "git svn rebase"
        if isGitSvn(path):
            cmd = "git svn rebase"
        else:
            cmd = "git pull"

        #print "It's a git repo, let's rebase", path, ":", cmd,
        if isDirty(path):
            #print "DIRTY!!!"
            dirty.append(path)
            cmd = "echo \"skipping, this one's dirty!\""
        #print cmd
    elif os.path.isdir(path + "/.svn/"):
        #print "It's a SVN repo, update ... ", p
        cmd = "svn up"
    if len(cmd):
      fullcmd = "cd %s && %s" % (path, cmd)
      print fullcmd
      ret = 0
      retcode = call(fullcmd, shell=True)
      #ret = os.system(fullcmd)
      if retcode > 0:
          othererror.append(path)
    else:
          othererror.append(path)
 
print "Errors:", othererror
print "Dirty:", dirty
