#!/usr/bin/env python

from optparse import OptionParser
import re
import sys
import os

parser = OptionParser()
parser.add_option("-p",action="store_true",dest="parent",default=False,help="make parent directories as needed")
options,args = parser.parse_args()

from rootpy.io.file import VALIDPATH

if len(args)==0:
    print "specify at least one directory"
    sys.exit(1)

for path in args:
    if path.endswith(".root"):
        from ROOT import TFile
        file = TFile.Open(path,"recreate")
        file.Close()
    else:
        match = re.match(re.compile(VALIDPATH),path)
        if match:
            from ROOT import TFile, gDirectory
            file = match.group('file')
            if not os.path.isfile(file):
                file = TFile.Open(file,"recreate")
            else:
                file = TFile.Open(file,"update")
            file.cd()
            dir = match.group('path')
            if dir.endswith('/'):
                dir = dir[:-1]
            fullpath = dir
            head,tail = os.path.split(dir)
            if tail == "":
                print "invalid directory name"
                sys.exit(0)
            if options.parent:
                ndirs = head.strip('/').split('/')
                for ndir in ndirs:
                    dir = gDirectory.GetDirectory(ndir)
                    if not dir:
                        dir = gDirectory.mkdir(ndir)
                    dir.cd()
                dir = gDirectory.GetDirectory(tail)
                if dir:
                    print "%s already exists"%fullpath
                    sys.exit(1)
                else:
                    gDirectory.mkdir(tail)
                    sys.exit(0)
            if head != "":
                dir = gDirectory.GetDirectory(head)
                if not dir:
                    print "%s does not exist."%head
                    print "Rerun with the -p option to recursively make subdirectories as needed."
                    sys.exit(1)
                dir.cd()
            dir = gDirectory.GetDirectory(tail)
            if dir:
                print "%s already exists"%fullpath
                sys.exit(1)
            gDirectory.mkdir(tail)
            file.Close()
        else:
            print "that is not a valid directory"
            sys.exit(1)
