#!/usr/bin/env python

# if this were built into Git, then you'd just type "git remote add $NAME
# $FURL". So this tool is named "git-remote-add-furl".

# likewise, the behavior that would be provided by an imaginary "git clone
# FURL" is implemented in "git-clone-furl"

import re, sys, subprocess
from twisted.python import usage
from os.path import exists, join

def probably_git_repo(repodir):
    return exists(join(repodir, "objects")) and exists(join(repodir, "refs"))

class Options(usage.Options):
    synopsis = "git-remote-add-furl REMOTENAME FURL"

    longdesc = """Add a flappserver-based 'remote repository' definition to
    the current Git repository. After doing this, 'git pull REMOTENAME' will
    pull from the remote repo associated with FURL (which should be prepared
    with the neighboring git-publish-with-furl script). 'git push REMOTENAME'
    will also work, if push was enabled by the remote repo.

    Setting REMOTENAME to 'origin' may be a good idea, especially if you
    expect to use this remote repository a lot."""

    def opt_h(self):
        return self.opt_help()

    def parseArgs(self, remote_name, furl):
        if re.search(r'[. "\']', remote_name):
            raise usage.UsageError("the remote name %s may not contain spaces, dots, or quotes" % remote_name)
        self.remote_name = remote_name
        if not furl.startswith("pb://"):
            raise usage.UsageError("second argument must be a FURL starting with pb://.. , and '%s' doesn't look like one" % furl)
        self.furl = furl
        if not probably_git_repo(".git") or not exists(".git/config"):
            raise usage.UsageError("The current directory does not look like a Git repository")

o = Options()
try:
    o.parseOptions()
except usage.UsageError, e:
    print "Error:", e
    print o
    sys.exit(1)

def call(*cmd):
    if len(cmd) == 1:
        print cmd[0]
        rc = subprocess.call(cmd[0], shell=True)
    else:
        print " ".join(cmd)
        rc = subprocess.call(cmd)
    if rc != 0:
        print >>sys.stderr, "ERROR"
        sys.exit(rc)

call("git", "config", "--add", "core.gitProxy","git-proxy-flappclient for furl")
call("git config --add core.gitProxy none")
call("git remote add %s git://%s.furl/" % (o.remote_name, o.remote_name))
call("git config --add remote.%s.furl %s" % (o.remote_name, o.furl))

print "Local tree is configured. Run 'git pull %s master' to pull." % o.remote_name
