#!/usr/bin/env python

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

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

class Options(usage.Options):
    synopsis = "git-publish-with-furl [--allow-push] SERVERDIR REPODIR"
    optFlags = [
        ("allow-push", "p", "allow client to push changes into this repository"),
        ]
    longdesc = """Add a service (to a pre-existing flappserver) that will
grant FURL-based access to a single Git repository in REPODIR. Use
'flappserver create' and 'flappserver start' to launch the server, then run
me to connect the server and a repository. I will emit a FURL, which can be
passed to 'git-clone-furl' and 'git-remote-add-furl' (on some other machine)
to create repos that can access my REPODIR."""

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

    def parseArgs(self, serverdir, repodir):
        serverdir = abspath(serverdir)
        if not exists(join(serverdir, "flappserver.tac")):
            print >>sys.stderr, "serverdir %s doesn't look like a flappserver basedir" % serverdir
            raise usage.UsageError("SERVERDIR must be a flappserver basedir")
        if not exists(join(serverdir, "umask")):
            print >>sys.stderr, "flappserver doesn't have --umask set: consider setting it to 022, otherwise permissions on working files may be messed up"
        self.serverdir = serverdir
        repodir = abspath(repodir)
        if not probably_git_repo(repodir):
            print >>sys.stderr, "repodir %s doesn't look like a bare git repo" % repodir
            if probably_git_repo(join(repodir, ".git")):
                print >>sys.stderr, "(but I see a .git subdirectory: please point me at that, or use a bare repo)"
            raise usage.UsageError("REPODIR must be a git repository")
        self.repodir = abspath(repodir)

o = Options()
o.parseOptions()

ok = join(o.repodir, "git-daemon-export-ok")
if not exists(ok):
    open(ok, "w").close()

comment = "allow read "
if o["allow-push"]:
    comment += "(and write) "
comment += "access to the Git repository at " + o.repodir
cmd = ["flappserver", "add", "--comment", comment, o.serverdir,
       "run-command", "--accept-stdin", "/",
       "git", "daemon", "--inetd", "--syslog",
       "--interpolated-path=%s" % o.repodir,
       ]
if o["allow-push"]:
    cmd.append("--enable=receive-pack")
os.execvp(cmd[0], cmd)
