import os, time, sys

timeFormat = "%Y-%m-%d-%H-%M-%S"
nowDir = "now"

def findPersifs():
    # Guess a good starting path (pwd is more friendly, but may not
    # have a good prefix)
    cwd, pwd = [os.path.normpath(path) for path in
                (os.getcwd(), os.getenv("PWD", os.getcwd()))]
    rest = ()

    # Check parent directories for .persifs
    while True:
        if not os.path.samefile(cwd, pwd):
            # The more friend pwd has diverged from the more correct cwd
            pwd = cwd

        if os.access(os.path.join(pwd, ".persifs"), os.R_OK):
            if len(rest) == 0:
                return pwd, "", ""
            elif len(rest) == 1:
                return pwd, rest[0], ""
            else:
                return pwd, rest[0], os.path.join(*rest[1:])

        cwd, tail1 = os.path.split(cwd)
        pwd, tail2 = os.path.split(pwd)
        if tail1 == "":
            # Hit root
            print "Current directory is not in persifs"
            sys.exit(1)
        rest = (tail1,) + rest

def pathAtTime(pd, path, ts):
    return os.path.join(pd,
                        time.strftime(timeFormat, time.localtime(ts)),
                        path)
