import subprocess as s
import io,os
from confstuff import remoteHost,remoteName

ssh = s.Popen(["ssh","-T",remoteHost],stdin=s.PIPE,stdout=s.PIPE)
inp = io.TextIOWrapper(ssh.stdin)

inp.write("cd ~/creation/stories\n")
inp.write("ls -d */.git\n")
inp.flush()
inp.close()

out = io.TextIOWrapper(ssh.stdout)
for line in out:
    line = line.rstrip()
    if not line.endswith("/.git"): continue
    name = line[:-len("/.git")]
    print('checking',name)
    if os.path.isdir(name):
        os.chdir(name)
        if 'push' in os.environ:
            pull=['git','push',remoteName,'master:pushed']
        else:
            pull=['git','pull']
        try: s.check_call(pull)
        except s.CalledProcessError:
            s.call(['git','remote','add',remoteName,remoteHost+':~/creation/stories/'+name])
            s.check_call(['git','fetch',remoteName])
            s.call(['git','branch','--set-upstream-to='+remoteName+'/master'])
            s.check_call(pull)
        os.chdir("..")
    elif not 'push' in os.environ:
        s.call(['git','clone',remoteHost+':~/creation/stories/'+name])

ssh.wait()
