#!/usr/bin/env python
#---------------------------------------------------------------------------------------------------
# Script to make a directory for the production
#
# Author: C.Paus                                                                      (Jan 08, 2011)
#---------------------------------------------------------------------------------------------------
import os,sys,getopt,re

def debugPrint(text):
    if debug == 1:
        print ' DEBUG: ' + text

def clean(file):
    if   re.search('dcap:',file):
        g = file.split('/')
        file = '/'.join(g[3:])
    debugPrint(' Cleaned: ' + file)

    return file

def exists(target):
    storagePath = '/srm/managerv2?SFN='
    if   re.search('/castor/cern.ch/',target):
        debugPrint(' Identified castor file')
        storageEle = 'srm-cms.cern.ch'
        storageUrl = 'srm://' + storageEle + ':8443' + storagePath + target
        cmd = 'srmls ' + storageUrl + ' >& /dev/null'
    elif re.search('/mnt/hadoop/cms/store/',target):
        debugPrint(' Identified tier-2 hadoop file')
        storagePath = '/srm/v2/server?SFN='
        storageEle = 'se01.cmsaf.mit.edu'
        storageUrl = 'srm://' + storageEle + ':8443' + storagePath + target
        cmd = 'srmls ' + storageUrl + ' >& /dev/null'
    else:
        debugPrint(' Identified a normal directory')
        cmd = 'ls -1 ' + target + ' >& /dev/null'
            
    status = os.system(cmd)
    debugPrint(' Status: %d (for: %s)' %(status,cmd))

    return (status == 0)

def makeDir(target):
    storagePath = '/srm/managerv2?SFN='
    if   re.search('/castor/cern.ch/',target):
        debugPrint(' Identified castor file')
        storageEle = 'srm-cms.cern.ch'
        storageUrl = 'srm://' + storageEle + ':8443' + storagePath + target
        cmd = 'srmmkdir ' + storageUrl + ' >& /dev/null' + \
              '; srm-set-permissions -type=ADD -owner=RWX -group=RWX -other=RWX ' + storageUrl
    elif re.search('/mnt/hadoop/cms/store/',target):
        debugPrint(' Identified tier-2 hadoop file')
        storagePath = '/srm/v2/server?SFN='
        storageEle = 'se01.cmsaf.mit.edu'
        storageUrl = 'srm://' + storageEle + ':8443' + storagePath + target
        cmd = 'srmmkdir ' + storageUrl + ' >& /dev/null' + \
              '; srm-set-permissions -type=ADD -owner=RWX -group=RWX -other=RWX ' + storageUrl
    else:
        debugPrint(' Identified a normal directory')
        cmd = 'mkdir ' + target

    # ready to perform the requested operation
    debugPrint('  -> makedir with: ' + cmd)
    status = 0
    if exe == 1:
        status = os.system(cmd)

    return status

#===================================================================================================
# Main starts here
#===================================================================================================
# Define string to explain usage of the script
usage =  "Usage: makedir  <target>"
usage += "                --exe\n"
usage += "                --debug\n"
usage += "                --help\n"

# Define the valid options which can be specified and check out the command line
valid = ['exe','debug','help']
try:
    opts, args = getopt.getopt(sys.argv[1:], "", valid)
except getopt.GetoptError, ex:
    print usage
    print str(ex)
    sys.exit(1)

# --------------------------------------------------------------------------------------------------
# Get all parameters for the production
# --------------------------------------------------------------------------------------------------
# Set defaults for each option
debug = 0
exe   = 0

# Read new values from the command line
for opt, arg in opts:
    #print ' OPT , ARG: ' + opt + ' ' + arg
    if   opt == '--help':
        print usage
        sys.exit(0)
    elif opt == '--debug':
        debug = 1
    elif opt == '--exe':
        exe   = 1

newArgv = []
for arg in sys.argv[1:]:
    #print ' ARG: ' + arg
    if arg[:2] == "--":
        continue
    else:
        newArgv.append(arg)

# cleanup the target
target = clean(newArgv[0])

# Test whether the target exists and make it if required
if   exists(target):
    debugPrint("\n No action required, target exists already: %s\n"%target)
elif not exists(target):
    print ' make directory ('+target+').'
    makeDir(target)
