#!/usr/bin/env python
'''
Created on 7 Jun 2010

@author: kreczko

Email: kreczko@cern.ch
'''
import sys, os
try:
    import subprocess
except:
    print "You have to use Python 2.4 or higher"
    sys.exit(0)
from optparse import OptionParser

srmBase = 'srm://srm-cms.cern.ch:8443/srm/managerv2?SFN=/castor/cern.ch/cms'
srmBaseCopy = 'srm://srm-cms.cern.ch:8443/srm/managerv2?SFN='

def getFiles(gridFolder, input):
    if gridFolder.endswith('/'):
        gridFolder = gridFolder.rstrip('/')
    input = input.rstrip(' ')
    fileLinesOnly = input[input.find(gridFolder) + len(gridFolder):]
    fileLines = fileLinesOnly.split('\n')[1:]
    fileLines = [fileLine.lstrip(' ') for fileLine in fileLines]
    files = [line.split(' ')[1] for line in fileLines if len(line.split(' ')) == 2]
    files.sort()
    return files
    
def listFiles(gridFolder):
    output = subprocess.Popen(['srmls', srmBase + gridFolder], stdout=subprocess.PIPE).communicate()[0]
    return output
    
def copySrm(file):
    ommitExisting = '-overwrite_mode=WHEN_FILES_ARE_DIFFERENT'
    protocolVersion = '-srm_protocol_version=2'
    output = subprocess.Popen(['srmcp', ommitExisting, protocolVersion, srmBase + file], stdout=subprocess.PIPE).communicate()[0]
    return ''

def copylcg(file, to):
    print '>> lcg-cp ' + srmBaseCopy + file + ' ' + to
    output = subprocess.Popen(['lcg-cp', srmBaseCopy + file, to], stdout=subprocess.PIPE).communicate()[0]
    return output

if __name__ == '__main__':
    
    parser = OptionParser()
    (options, args) = parser.parse_args()
    if len(args) > 0:
        path = args[0]
        filelist = listFiles(path)
        for file in getFiles(path, filelist):
            filename = file.split('/')[-1]
            if not os.path.exists(filename):
                to = os.getcwd() + '/' + filename
                print 'Copying file', srmBase + file
                copylcg(file, to)
                print
            else:
                print filename, 'already exists'
    else:
        print 'Copy path was not specified. Use script "./copyGridFolder path"'
