#!/bin/sh
#
# Ricardo Goncalo - painlessly copy of files from and to castor
# 24/4/2008
#
# error protection
getopts duh option
case $option in
    h)     echo " "
           echo "Move files to and from CASTOR "
	   echo " "
	   echo "usage : castorcopy.sh [-tfh] [dir1] [dir2]"
	   echo "   -s : pre-stage files in castor and then download"
	   echo "   -d : download files from castor dir1 to local dir2"
	   echo "   -u : upload files from local dir1 to castor dir2"
	   echo "   -h : print this help"
	   echo " "
	   exit 0
    ;;
esac

if [ $# -ne 3 ]
then 
    echo "Error: not enough arguments; use castorcopy.sh -h"
    exit 1
fi

# get directory names
dir1=$2
dir2=$3

# get options
#while getopts duh option
#do 
  echo "option $option"
  case $option in
      s)  echo "Staging and downloading files from castor"
          nsls $dir1 > tmp_ls.txt
	  while read file
	    do
	    echo "staging "$file" from "$dir1
	    stager_get -M $dir1/$file
	  done < tmp_ls.txt
	  while read file
	    do
	    echo "copying "$file" from "$dir1" to "$dir2
	    rfcp $dir1/$file $dir2
	  done < tmp_ls.txt
	  ;;
      d)  echo "Downloading files from castor"
          nsls $dir1 > tmp_ls.txt
	  while read file
	    do
	    echo "copying "$file" from "$dir1" to "$dir2
	    rfcp $dir1/$file $dir2
	  done < tmp_ls.txt
	  ;;
      u)  echo "Uploading files to castor"
          ls -1 $dir1 > tmp_ls.txt
	  while read file
	    do
	    echo "copying "$file" from "$dir1" to "$dir2
	    rfcp $dir1/$file $dir2
	  done < tmp_ls.txt
	  ;;
      h)  echo " "
	  echo "Move files to and from CASTOR "
	  echo " "
	  echo "usage : castorcopy.sh [-tfh] [dir1] [dir2]"
	  echo "   -s : pre-stage files in castor and then download"
	  echo "   -d : download files from castor dir1 to local dir2"
	  echo "   -u : upload files from local dir1 to castor dir2"
	  echo "   -h : print this help"
	  echo " "
	  exit 0
	  ;;         
      \?) echo "0$: unknown option (duh allowed)"
          exit 1
	  ;;
   esac
#done 

# cleanup
rm -f tmp_ls.txt
