#!/bin/env python3
import argparse
import yaml
import shutil
import subprocess
import os
import sys

#read commmand line arguments
parser = argparse.ArgumentParser()
parser.add_argument( 'config_file' )
args = parser.parse_args()
sys.stderr.write ("Reading from {0}\n".format( args.config_file ) )

#load config file
config_file = open ( args.config_file )
config = yaml.load( config_file )

#get mission file
mission = config['run']['mission']

#get output options
save = config['save']

#do local
for source, dest in save['local'].items():
    sys.stderr.write ( "Copying {0} to {1}\n".format( source, dest ))
    os.makedirs( os.path.dirname( dest ), exist_ok = True )
    try:
        shutil.copy( source, dest )
    except IOError:
        print( 'Could not copy {0} to {1}\n'.format( source, dest ) )


#do castor
for source, dest in save['castor'].items():
    sys.stderr.write ( "Copying {0} to {1}\n".format( source, dest ))
    subprocess.check_call( ['rfmkdir', '-p',
            os.path.dirname(dest)] )
    subprocess.check_call(['rfcp', source, dest] )

for source, dest in save['eos'].items():
    sys.stderr.write ( "Copying {0} to {1}\n".format( source, dest ))
    subprocess.check_call( ['/afs/cern.ch/project/eos/installation/0.3.15/bin/eos.select', 'mkdir', '-p',
            os.path.dirname(dest)] )
    subprocess.check_call(['xrdcp', source, 'root://eosna62//' + dest] )
