#!/usr/bin/perl -w

##########################################################################################
#
#  globalSuite[.pl]
#
#  A Perl script to test the DPM (all interfaces + more)
#
#  Author: Gilbert Grosdidier, LAL (Universite Paris-Sud, Orsay)
#  Creation Date:  06/07/2005
#  Last rev:       04/02/2008 (GG)
#
##########################################################################################

###
### Copyright (C) 2005-2008 by CNRS/IN2P3/LAL
### All rights reserved
###

# $Id: globalSuite,v 1.42 2008/02/05 05:46:05 grodid Exp $

use strict;
no strict 'refs';
use File::Basename;
use Getopt::Long;

## Arg fetching ...
my $mach   = shift;
##my $many   = shift;
##my $label  = shift;
chomp(my $site_domain = `dnsdomainname`);
my $proxyT = shift || "globus";  ##  Allowed: globus, voms, vomsR, expired, extern
## Remark: vomsR -> ppdg only;
my $certA  = shift || "NADA";    ##  Allowed: NADA, ppdg, cnrs, cern, lhcb, ops
## Remark: lhcb VO -> ppdg; ops VO -> cern;
my $domain = shift || "$site_domain";
my $fmach = "$mach.$domain";

## Inits ...
my $Counter; 
my $user = $ENV{USER};
my $valinc;
my $short = $mach;
my $sfile;
my $xCount = 0;
my $globOK = 0;
my $globFD = 0;
my $operation;
my $dateST;
my $command;
my $proxyI;
my $userI;
my @res = ();
my @m   = ();
my @dServer = ();
my $dServer0;
my $status;
my $statusLocal;
my $result;
my $flat;
chomp(my $dday = `date '+%j'`);
chomp(my $Dday = `date '+%F'`);
chomp(my $Hday = `date '+%H%M%S'`);
my $otStart = time();
if ( ! $sfile ) {
##F    $Counter = File::CounterFile->new("./CounterFile", 1000+$dday);
##F    $valinc = $Counter->inc();
    $valinc = "$Hday";
    $sfile = "fil$valinc";
    print " Counter Start Value: $sfile \n";
}
my $statDone = 'Done';
#my $statDone = 'Ready';

my $choiceVO = 'dteam';
my $userD;
if ( $certA eq 'NADA' ) {
    $userD = "$ENV{USER}";
    $userI = 'N';
} elsif ( $certA eq 'ppdg' ) {
    $userD = "$ENV{USER}p";
    $userI = 'P';
} elsif ( $certA eq 'cnrs' ) {
    $userD = "$ENV{USER}c";
    $userI = 'C';
} elsif ( $certA eq 'cern' ) {
    $userD = "$ENV{USER}g";
    $userI = 'G';
} elsif ( $certA eq 'lhcb' ) {
    $userD = "$ENV{USER}l";
    $userI = 'L';
    $choiceVO = 'lhcb';
} elsif ( $certA eq 'ops' ) {
    $userD = "$ENV{USER}s";
    $userI = 'S';
    $choiceVO = 'ops';
}

##Fmy $tempDir = "/tmp/grodid/global/$mach/$sfile";
my $tempDir = "/var/tmp/${userD}/global/$mach/$Dday/$sfile";
my $logFile = "$tempDir/logFile";
system("mkdir -p $tempDir");
print " Printing to: $logFile\n";
my $fhlRef = switchStdouterr($logFile);
print " Counter Start Value: $sfile \n";

my $dpmRoot = "/dpm/${domain}/home/$choiceVO";
##Fmy $pfxPath = "grodid/tglob/S$valinc";
my $pfxPath = "${userD}/tglob/M$mach/D$Dday/H$valinc";
my $endPointV1 = "srm://${fmach}:8443/srm/managerv1?SFN=";
my $endPointV2 = "srm://${fmach}:8446/srm/managerv2?SFN=";

## Local proxy creation ... moved down ...
##&CreateProxy();

## Env Vars
## Alternate (SLC3TB BDII in fact)
$ENV{LCG_GFAL_INFOSYS} = "lxb2017.cern.ch:2170";
##GOODD$ENV{LCG_GFAL_INFOSYS} = "lxb2033.cern.ch:2170";
## Alternate (RH73TB BDII in fact)
##$ENV{LCG_GFAL_INFOSYS} = "lxb1916.cern.ch:2170";
## Local GRIS
$ENV{LCG_GFAL_INFOSYS} = "$fmach:2135";

chomp(my $lmach = `hostname -s`);
if ( $lmach eq 'lxb0728' ) {
    $ENV{LCG_GFAL_INFOSYS} = "lxb0728.cern.ch:2170";
}

if (0) {
##if ( $mach =~ 'lxb1903' || $mach =~ 'lxb5407' ) {
if ( $mach eq 'lxb1903' || $mach eq 'lxb5407' ) {
    $ENV{LCG_GFAL_INFOSYS} = 'lxb0728.cern.ch:2170';
## For testing Remi's version ...
$ENV{LCG_LOCATION} = '/afs/cern.ch/project/gd/rmollon/usr';
##$ENV{LCG_LOCATION} = '/afs/cern.ch/project/gd/grodid/gfal';
$ENV{LD_LIBRARY_PATH} = "$ENV{LCG_LOCATION}/lib:/opt/lcg/lib:/opt/globus/lib:/opt/edg/lib:/usr/local/lib:/usr/local/lib:/usr/local/lib:/opt/glite/lib:/opt/glite/externals/lib:/opt/d-cache/dcap/lib:/opt/glite/lib:/opt/glite/externals/lib:/opt/d-cache/dcap/lib:/opt/glite/lib:/opt/glite/externals/lib:/opt/d-cache/dcap/lib";
}
}

## To control use of standard lcg_util version
my $stdSwitch = 1;
if ($stdSwitch) { # Temporary (?) removal to use default version (20/11/07) 
##if ( $mach eq 'lxb1727' || $mach eq 'lxb1921' ) {
if ( $mach eq 'lxb1921' || $mach eq 'lxb1917' || $mach eq 'lxb5407' || $mach eq 'lxb1903' || $mach eq 'lxb1727' || $mach eq 'lxb1902' || $mach eq 'lxdpm102' || $mach eq 'lxb2036' || $mach eq 'lxb6132v2' || $mach eq 'lxb0988v2' || $mach eq 'ctb-conf-se' || $mach eq 'ctb-conf-bdii' || $mach eq 'vm02-lxb6121' || $mach eq 'pcitdhs02' ) {
    ## For testing Remi's version ...
    $ENV{LCG_LOCATION} = '/afs/cern.ch/project/gd/rmollon/usr';
##GOODOLD    $ENV{LCG_LOCATION} = '/afs/cern.ch/project/gd/grodid/gfal';
##    $ENV{LCG_LOCATION} = '/afs/cern.ch/project/gd/grodid/gfal-150607';
##USELESS    $ENV{LCG_LOCATION} = '/afs/cern.ch/project/gd/grodid/gfal-260607';
##    $ENV{LCG_LOCATION} = '/afs/cern.ch/project/gd/grodid/gfal-221107';
##    $ENV{LCG_LOCATION} = '/afs/cern.ch/project/gd/grodid/gfal-231107';
##GOODSLC3    $ENV{LCG_LOCATION} = '/afs/cern.ch/project/gd/grodid/gfal-dev2/usr';
    ###$ENV{LD_LIBRARY_PATH} = "$ENV{LCG_LOCATION}/lib:/opt/lcg/lib:/opt/globus/lib:/opt/edg/lib:/usr/local/lib:/usr/local/lib:/usr/local/lib:/opt/glite/lib:/opt/glite/externals/lib:/opt/d-cache/dcap/lib:/opt/glite/lib:/opt/glite/externals/lib:/opt/d-cache/dcap/lib:/opt/glite/lib:/opt/glite/externals/lib:/opt/d-cache/dcap/lib";
    $ENV{LD_LIBRARY_PATH} = "$ENV{LCG_LOCATION}/lib:$ENV{LD_LIBRARY_PATH}";
    $ENV{PATH} = "$ENV{LCG_LOCATION}/bin:$ENV{PATH}";
}
}

if ( $mach eq 'lxb1727' ) {
    $ENV{LCG_GFAL_INFOSYS} = "$fmach:2135";
}

##if ( $mach eq 'lxb1921' ) { ## 07/05/07 ## 15/11/07
if ( $mach eq 'lxb1921' || $mach eq 'lxb5407' || $mach eq 'lxb1903' || $mach eq 'lxb1727' || $mach eq 'lxb1902' || $mach eq 'lxdpm102' || $mach eq 'lxb6132v2' || $mach eq 'lxb0988v2' || $mach eq 'ctb-conf-se'  || $mach eq 'ctb-conf-bdii' || $mach eq 'vm02-lxb6121' || $mach eq 'lxb1917' || $mach eq 'pcitdhs02' ) {
    $ENV{LCG_GFAL_INFOSYS} = "lxb1903.cern.ch:2135";
}

##if ( $mach eq 'lxb1921' || $mach eq 'lxb1917' || $mach eq 'lxb2036' ) {
#if ( $mach eq 'lxb1917' || $mach eq 'lxb2036' ) {
if ( $mach eq 'lxb2036' ) {
    $ENV{LCG_GFAL_INFOSYS} = "lxb2033.cern.ch:2170";
##    $ENV{LCG_GFAL_INFOSYS} = "lxb1917.cern.ch:2170";
}

$ENV{DPNS_HOST} = "$fmach";
$ENV{DPM_HOST}  = "$fmach";
$ENV{LCG_RFIO_TYPE} = "dpm";
$ENV{LCG_CATALOG_TYPE} = "lfc";
$ENV{LFC_HOME} = "/grid/$choiceVO/nightly/$userD";
$ENV{LFC_HOME} = "/grid/$choiceVO/nightly/$pfxPath";
## To define LFC_HOST as well !
$ENV{LFC_HOST} = "lfc-dteam-test.cern.ch";  ##  NEW:29/08/05
####$ENV{LFC_HOST} = "lxb0716.cern.ch";  ##  SPECIAL:17/11/05 tests Sophie 
$ENV{LFC_HOST} = "lxb1941.cern.ch";  ##  NEW: 10/02/06 MySQL, SLC3TB
##$ENV{LFC_HOST} = "lxb1782.cern.ch";  ##  NEW: 03/10/06 Oracle, SLC3TB
$ENV{LFC_HOST} = "lxb6129.cern.ch";  ##  NEW: 18/01/08 Louis
print " Testing DPM server: $fmach ($mach) with LCG_GFAL_INFOSYS: $ENV{LCG_GFAL_INFOSYS} and LFC_HOST: $ENV{LFC_HOST}\n";
##print " Testing DPM server: $mach with LCG_GFAL_INFOSYS: $ENV{LCG_GFAL_INFOSYS}\n";

## Path setup ... one must start it from test/dpm for the time being ...
##my $relPath = "/afs/cern.ch/project/gd/grodid/SLC3-CVS-dpm-133-n/LCG-DM";

my $relPath = dirname (dirname "$ENV{PWD}");
##my $relPathLBNL = dirname (dirname "$relPath");
##$relPathLBNL = "$relPathLBNL/SLC3-CVS-dpm-140-lbnl/LCG-DM/test/srmv2";
my $relPathLBNL = "$relPath/test/srmv2-lbnl";
my $pathStore = $ENV{PATH};

#    $ENV{PATH} = "../../rfio:$ENV{PATH}";
##    $ENV{PATH} = "$relPath/rfio:$ENV{PATH}";
    $ENV{PATH} = "$relPath/rfio";
    $ENV{PATH} = "$ENV{PATH}:$relPath/socket/dpmcli";
    $ENV{PATH} = "$ENV{PATH}:$relPath/ns";
    $ENV{PATH} = "$ENV{PATH}:$relPath/dpm";
    $ENV{PATH} = "$ENV{PATH}:$relPath/test/srmv1";
    $ENV{PATH} = "$ENV{PATH}:$relPath/test/srmv2";
    $ENV{PATH} = "$ENV{PATH}:$relPath/test/dpm";

    $ENV{PATH} = "$ENV{PATH}:$pathStore";

print " Testing DPM server: $fmach ($mach) with LD_LIBRARY_PATH: $ENV{LD_LIBRARY_PATH}\n";
print " Testing DPM server: $fmach ($mach) with PATH: $ENV{PATH}\n";
system("which lcg-gt");

##Cchdir "/afs/cern.ch/user/g/grodid/public/grid/tar/CVS-tar-0.1.15/localGfalTest";
chdir $tempDir;
$ENV{TEMPDIR} = $tempDir;
$ENV{VOTEAM}  = $choiceVO;

if ( $mach eq 'lxb1917' ) {
    system("mysql_process.sh");
}

## Local proxy creation
&CreateProxy();
$sfile = "$sfile" . "$userI" . "$proxyI";
print " Counter Start Value: $sfile \n";

system("env|grep -v 'GSI_'|sort");
system("which rfcp");
system("voms-proxy-info -all");
system("which srm2_testPut");

if (0) {
my %vogid = ();
my %vonid = ();
my %voaid = ();
## Extracting the user/group codes from the remote DPM node PWD/GRP files
system("globus-url-copy gsiftp://${mach}.cern.ch/${mach}:/etc/passwd file://$tempDir/${mach}_PWD");
system("globus-url-copy gsiftp://${mach}.cern.ch/${mach}:/etc/group  file://$tempDir/${mach}_GRP");
foreach my $grp ( "atlas", "cms", "dteam" ) {
    my ($auid, $ux, $uid, $gid, $rest) = split /:/, `grep ${grp}006 $tempDir/${mach}_PWD`;
    $vogid{$grp} = $gid;
    my ($mode, $ix, $irt, $aid, $nest) = split /\s+/, `dpns-ls -ld /dpm/${site_domain}/home/${grp}`;
    $voaid{$aid} = $gid;
    $vonid{$gid} = $aid;
    print " GRP: $grp, GID: $gid, AID: $aid\n";
}
my %duser = ();
foreach my $nid ( 1, 4, 5, 6 ) {
    my ($auid, $ux, $uid, $gid, $rest) = split /:/, `grep dteam00$nid $tempDir/${mach}_PWD`;
    $duser{$auid} = $uid;
    $duser{$uid} = $auid;
    print " DTEAM: AUID: $auid, UID: $uid\n";
}
}
##exit 0;

XcuteComm("dpm-qryconf",
	  "", 
	  "QRY", 1,
	  "S_TYPE", "",
	  "POOL");
foreach ( @res ) {
    if ( /CAPACITY/ ) {
	my @m = split /\s+/;
	if ( $m[3] eq "CAPACITY" && $m[-1] !~ m/RDONLY|DISABLED/ ) { 
	    push @dServer, $m[1];
	    if ( $m[1] ne $fmach ) { $dServer0 = $m[1]; }
	}
    }
}
print(" dServer: $#dServer $dServer0 \n");
##exit 0;  ##  Tests vomses

## Management of different message classes for different GridFTP Server versions ...
my %gsiftpV = ();
my %gsiLsMs= ();
$gsiLsMs{'1.12'} = "taken.: No such file or";
$gsiLsMs{'2.3'}  = "stat error: No such file or";
$gsiLsMs{'2.7'}  = "stat error: No such file or";
my %gsiRmdMs= ();
$gsiRmdMs{'1.12'} = "subgDirS1: Directory not";
$gsiRmdMs{'2.3'}  = "500 500 Command failed : rmdir error:";
$gsiRmdMs{'2.7'}  = "500 500 Command failed : rmdir error:";
my %gsiTrfMs= ();
$gsiTrfMs{'1.12'} = "226 Transfer complete";
$gsiTrfMs{'2.3'}  = "226 Transfer Complete";
$gsiTrfMs{'2.7'}  = "226 Transfer Complete";
## Detection of the different GridFTP Server versions for the target DPM ...
foreach my $serv ( @dServer ) {
    if ( defined $gsiftpV{$serv} ) { next; }
    XcuteComm("globus-url-copy",
	      "-dbg file:/etc/group gsiftp://${serv}/${serv}:/dumDUM",
	      "DUM_$serv", 0,
	      "BLOCK", "",
	      "GridFTP Server");
    my $vval = $result;
#??    my $sval = XtractVal("DUM_$serv: 220 $serv GridFTP Server");
    my $sval = XtractVal('^220');
    if ( $sval ne $serv ) { exit 1; }
    $gsiftpV{$sval} = "$vval";
}

if ( $ENV{TSRMV22} ) {
$ENV{PATH} = "$relPath/test/srmv2.2:$ENV{PATH}";
## srmv2.2Suite
XcuteComm("srmv2Suite",
	  "$fmach 8446 $user $sfile $choiceVO $pfxPath", 
	  "SRV22", 0,
	  "OVERALL SUITE =", "[OK]",
	  "SURL =");
# @m = grep /GID4:.*?Done OK/, @res;
# @m = split /\s+/, $m[0];
print " srm10: $result\n";
(my $srm10 = $result) =~ s/8446/8443/;;
@m = split /\//, $srm10;
my $lfn10 = $m[-1];
## Temporaire tests SSL3
exit 0; 
}

if (1) {
XcuteComm("lfc-ping",
	  " ", 
	  "LFCPNG", 0,
	  "1.6", "",
	  "BLOB");

XcuteComm("dpns-ping",
	  " ", 
	  "DPNSPNG", 0,
	  "1.6", "",
	  "BLOB");

XcuteComm("dpm-ping",
	  " ", 
	  "DPMPNG", 0,
	  "1.6", "",
	  "BLOB");
}

XcuteComm("dpns-mkdir -p",
	  "$dpmRoot/$pfxPath", 
	  "DMKD", 0,
	  "BLOCK", "",
	  "BLOB");

XcuteComm("lfc-mkdir -p",
	  "$ENV{LFC_HOME}", 
	  "LMKD", 0,
	  "BLOCK", "",
	  "BLOB");

XcuteComm("dpns-ls -ild",
	  "$dpmRoot/$pfxPath", 
	  "LSD", 1,
	  "$dpmRoot/$pfxPath", "",
	  "$dpmRoot/$pfxPath");
if ( "$result" ne "$dpmRoot/$pfxPath" ) { exit 1; }

XcuteComm("lfc-ls -ild",
	  "$ENV{LFC_HOME}", 
	  "LLSD", 1,
	  "$ENV{LFC_HOME}", "",
	  "BLOB");

## Investigations : look if the SRMV2 server is an LBNL version (assume default: it is NOT)
my $dpmb = "$dpmRoot/$pfxPath/bidon";
my $srmb = "srm://$fmach:8444/$dpmb";
######my $rstate;
my $rstate = 1;
if (0) {
#XcuteComm("srm2_testPut",
#	  "gutokenbidon 1 0 $srmb 1000 2 8",
#	  "LBNL0", 0,
#	  "HTTP/1.1 500 Internal Server", "Error",
#	  "BLOB");
#if ( $status eq "[OK]" ) {
#    $ENV{PATH} = "$relPathLBNL:$ENV{PATH}";
#    XcuteComm("srm2_testPut",
#	      "gutokenbidon 1 0 $srmb 1000 2 8",
#	      "LBNL1", 1,
#	      "request state", "26",
#	      "BLOB");
#}
#} else {

    if ( $mach eq 'lxb1903notanymore' ) {
	$rstate = 1;  ##  kludge for SLC4 testing ...
    } elsif (1) { 

XcuteComm("srm2_testPut",
	  "gutokenbidon 1 0 $srmb 1000 2 8",
	  "LBNL0", 0,
	  "BLOCK", "",
	  "HTTP/1.1 500 Internal Server");
if ( $result eq "Error" ) {
    $ENV{PATH} = "$relPathLBNL:$ENV{PATH}";
    XcuteComm("srm2_testPut",
	      "gutokenbidon 1 0 $srmb 1000 2 8",
	      "LBNL1", 0,
	      "BLOCK", "",
	      "request state");
    if ( "$result" ne "0" ) { exit 1; }
}
$rstate = XtractVal('request state');
##system("dpm-rm $dpmb");
    XcuteComm("dpm-rm",
	      "$dpmb",
	      "LBNL2", 1,
	      "request state", "Done",
	      "BLOB");

}
}
    if ( $rstate == 26 ) {
	$ENV{STAT26} = '26';
	$statDone = 'Done';
	print STDOUT "\n The (Old) Selected Return Status System is: stat26: $ENV{STAT26} statDone: $statDone \n";
    } else {
	$statDone = 'Ready';
	print STDOUT "\n The (New) Selected Return Status System is: stat26: 0 statDone: $statDone \n";
    }
##exit 0;
######}

my $gfalC = "gfal_test.c";
&createGfalTestC("$gfalC");

if (0) {
system("ldapsearch -LLL -H ldap://lxb2033.cern.ch:2170 -x -b 'mds-vo-name=local,o=grid' | grep -E 'GlueSEUniqueID|GlueSEName' | grep -B1 'GlueSEName: CERNDpmTest:' 2>&1 &");
print " System1: $?\n";
system("ldapsearch -LLL -H ldap://$ENV{LCG_GFAL_INFOSYS} -x -b 'mds-vo-name=local,o=grid' | grep -E 'GlueSEUniqueID|GlueSEName' | grep -B1 'GlueSEName: CERNDpmTest:' 2>&1 &");
print " System2: $?\n";
}

my $finit1 = "gilb-OLD";
&createGilbOld($finit1, $gfalC);
$finit1 = "$tempDir/$finit1";
my $lfn1   = "ggtgloblcgcr$sfile";
system("which lcg-cr");
if (1) {
##Added '-t 20' below for timeouting ...
XcuteComm("lcg-cr",
	  "-v -t 20 --vo $choiceVO -d $fmach -l lfn:$lfn1 -P $pfxPath/$lfn1 file:$finit1",
	  "LCR", 0,
	  "Alias registered in Catalog:", "lfn:$ENV{LFC_HOME}/$lfn1",
	  "Destination URL registered in Catalog:");
} else {
XcuteComm("lcg-cr",
	  "-v --vo $choiceVO -d $fmach -P $pfxPath/$lfn1 file:$finit1",
	  "LCR", 0,
	  "Alias registered in Catalog:", "",
	  "Destination URL registered in Catalog:");
}
my $sfn1 = $result;
(my $srm1 = $result) =~ s/sfn/srm/;

## Testing srmv2 interface ...
if (1) {
###if ( ! $stdSwitch ) {
my $lfnv1   = "ggtglobsrmv1$sfile";
XcuteComm("lcg-cr",
          "-v -t 20 -D srmv1 --nobdii --vo $choiceVO -d $endPointV1/$dpmRoot/$pfxPath/$lfnv1 -l lfn:$lfnv1 file:$finit1",
          "LCR", 0,
          "Alias registered in Catalog:", "lfn:$ENV{LFC_HOME}/$lfnv1",
          "Destination URL registered in Catalog:");
######          "-v -t 20 -D srmv2 --vo $choiceVO -d $fmach -l lfn:$lfnv2 -P $pfxPath/$lfnv2 file:$finit1",
my $lfnv2   = "ggtglobsrmv2$sfile";
XcuteComm("lcg-cr",
          "-v -t 20 -D srmv2 --nobdii --vo $choiceVO -d $endPointV2/$dpmRoot/$pfxPath/$lfnv2 -l lfn:$lfnv2 file:$finit1",
          "LCR", 0,
          "Alias registered in Catalog:", "lfn:$ENV{LFC_HOME}/$lfnv2",
          "Destination URL registered in Catalog:");
###}
}

if ( "$mach" eq "lxb5407" && ! $ENV{CRON_JOB}) {
    &dicomTests();
    goto EXITE;
}

###goto EXITE;
####exit 0;  ##  SPECIAL tests Invalid

XcuteComm("lcg-gt",
	  "$srm1 rfio",
	  "GTR", 0,
	  "rfio", "",
	  "rfio");
my $rTURL = XtractGoodTurl($result);
XcuteComm("rfcp",
	  "$rTURL $tempDir/fcrap1r", 
	  "TURLr", 0,
	  "seconds through eth", "",
	  "BLOB");

XcuteComm("lcg-gt",
	  "$srm1 gsiftp",
	  "GTF", 0,
	  "gsiftp", "",
	  "gsiftp");
my $fTURL = XtractGoodTurl($result);
my @m1 = split '/', $fTURL;
XcuteComm("globus-url-copy",
	  "-dbg $fTURL file:$tempDir/fcrap1f", 
	  "TURLf", 0,
	  "$gsiTrfMs{$gsiftpV{$m1[2]}}", "",
	  "BLOB");
##	  "226 Transfer complete.", "",
##my $gsiftpV = XtractVal('GridFTP Server');

## Crosscheck ...
XcuteComm("dpns-ls -il",
	  "$dpmRoot/$pfxPath", 
	  "LSD", 0,
	  "$lfn1", "",
	  "BLOB");

###goto EXITE;
####exit 0;  ##  Tests LFC_HOST ...

my $rinit2 = "DPMsource.lxb1706";
createDpmSource($rinit2);
##my $finit2 = "file:$ENV{PWD}/$rinit2";
my $finit2 = "file:$tempDir/$rinit2";
my $lfn2   = "ggtglobr$sfile";
## Direct rfcp ...
XcuteComm("rfcp",
	  "$rinit2 $dpmRoot/$pfxPath/$lfn2", 
	  "RFCP", 0,
	  "seconds through local", "",
	  "BLOB");

XcuteComm("rfcp",
	  "$dpmRoot/$pfxPath/$lfn2 $tempDir/fcrap2", 
	  "FCPR", 0,
	  "seconds through eth", "",
	  "BLOB");

## Crosscheck ...
XcuteComm("dpns-ls -il",
	  "$dpmRoot/$pfxPath", 
	  "LSDR", 0,
	  "$lfn2", "",
	  "BLOB");

$xCount++;

####$dServer0 = 'lxb1903.cern.ch';

my $tmach = "$fmach";

#if ( $tmach eq 'lxb1903.cern.ch' ) {  ##  Special since there is only 1 remote disk server on this DPM node
#    $tmach = "$dServer0";
#    undef $dServer0;
#}

&rfioSuite("DPM", $tmach);

&rfioSuite("NODPM", $tmach);

&gsiftpSuite("DPM", $tmach);

&gsiftpSuite("NODPM", $tmach);

if ( $dServer0 ) {
    undef $dServer0;

    &rfioSuite("NODPM", $tmach);

    &gsiftpSuite("DPM", $tmach);

    &gsiftpSuite("NODPM", $tmach);
} else {
    $xCount += 3;
}

####exit 0;
$xCount--;

my $lfn3   = "ggtglobf$sfile";
## Direct globus-url-copy ...
XcuteComm("globus-url-copy",
	  "-dbg $finit2 gsiftp://$tmach/$dpmRoot/$pfxPath/$lfn3", 
	  "GFTP", 0,
	  "$gsiTrfMs{$gsiftpV{$tmach}}", "",
	  "BLOB");
##	  "226 Transfer complete.", "",

XcuteComm("globus-url-copy",
	  "-dbg gsiftp://$tmach/$dpmRoot/$pfxPath/$lfn3 file:$tempDir/fcrap3", 
	  "FTPG", 0,
	  "$gsiTrfMs{$gsiftpV{$tmach}}", "",
	  "BLOB");
##	  "226 Transfer complete.", "",

## Crosscheck ...
XcuteComm("dpns-ls -il",
	  "$dpmRoot/$pfxPath", 
	  "LSDF", 0,
	  "$lfn3", "",
	  "BLOB");

my $lfn4   = "gfal_Tfile.$sfile";
#PRODGOODPREVmy $srm4   = "srm://$fmach:8443/$dpmRoot/$pfxPath/$lfn4";
##GOOD1my $srm4   = "srm://$fmach:8446/$dpmRoot/$pfxPath/$lfn4";
my $srm46   = "srm://$fmach:8446/$dpmRoot/$pfxPath/${lfn4}c";
my $srm4v2  = "srm://$fmach/srm/managerv2?SFN=$dpmRoot/$pfxPath/${lfn4}d";
##GOOD2my $srm4   = "srm://${fmach}/$dpmRoot/$pfxPath/$lfn4";
##GOOD3my $srm4   = "srm://${fmach}:8443/$dpmRoot/$pfxPath/$lfn4";
my $srm43   = "srm://$fmach:8443/$dpmRoot/$pfxPath/${lfn4}a";
my $srm4v1  = "srm://$fmach/srm/managerv1?SFN=$dpmRoot/$pfxPath/${lfn4}b";
#BAD?my $srm4   = "srm://${fmach}$dpmRoot/$pfxPath/$lfn4";
my $srmv4 = $srm46;
##my $finit4 = "../gftest.gg";
my $finit4 = "gftest.gg";
&createGftest($finit4);
## gfal ...
if (0) {
    my $gfalC = "gfal_test.c";
    &createGfalTestC("$gfalC");
}

## For testing Remi's version ... Moved upstream ...
### $ENV{LCG_LOCATION} = '/afs/cern.ch/project/gd/rmollon/usr';
### $ENV{LD_LIBRARY_PATH} = "$ENV{LCG_LOCATION}/lib:/opt/lcg/lib:/opt/globus/lib:/opt/edg/lib:/usr/local/lib:/usr/local/lib:/usr/local/lib:/opt/glite/lib:/opt/glite/externals/lib:/opt/d-cache/dcap/lib:/opt/glite/lib:/opt/glite/externals/lib:/opt/d-cache/dcap/lib:/opt/glite/lib:/opt/glite/externals/lib:/opt/d-cache/dcap/lib";

## Testing SRMV1 syntax ...
system("gcc -Wall -g -DSRM=1 -I $ENV{LCG_LOCATION}/include -L$ENV{LCG_LOCATION}/lib -lgfal -o gfal_test $gfalC");
##system("gcc -I /opt/lcg/include -L/opt/lcg/lib -lgfal_pthr -o gilb $gfalC");
XcuteComm("./gfal_test",
	  "-g 4 -D $tempDir -R -W $finit4 $srm43", 
	  "GFALa", 0,
	  "srm_get: 3", "",
	  "surl: 3");
##my $srm4Y = $result;
##	  "-g 7 -D $tempDir -R -W $finit4 $srm4", 

## Crosscheck ...
XcuteComm("dpns-ls -il",
	  "$dpmRoot/$pfxPath", 
	  "LSDYa", 0,
	  "${lfn4}aYY", "",
	  "BLOB");

XcuteComm("./gfal_test",
	  "-g 4 -D $tempDir -R -W $finit4 $srm4v1", 
	  "GFALb", 0,
	  "srm_get: 3", "",
	  "surl: 3");
XcuteComm("dpns-ls -il",
	  "$dpmRoot/$pfxPath", 
	  "LSDYb", 0,
	  "${lfn4}bYY", "",
	  "BLOB");

###goto EXITE;
 
## Testing SRMV2 syntax ...
##system("gcc -Wall -g -DSRM=2 -I $ENV{LCG_LOCATION}/include -L$ENV{LCG_LOCATION}/lib -lgfal -o gfal_test $gfalC");
system("gcc -Wall -g -DSRM=2 -D_LARGEFILE64_SOURCE -I $ENV{LCG_LOCATION}/include -L$ENV{LCG_LOCATION}/lib -lgfal -o gfal_test $gfalC");
##system("gcc -I /opt/lcg/include -L/opt/lcg/lib -lgfal_pthr -o gilb $gfalC");
XcuteComm("./gfal_test",
	  "-g 7 -D $tempDir -R -W $finit4 $srm46", 
	  "GFALc", 0,
	  "srm_get: 6", "",
	  "surl: 6");
my $srm4Y = $result;
##	  "-g 7 -D $tempDir -R -W $finit4 $srm4", 

## Crosscheck ...
XcuteComm("dpns-ls -il",
	  "$dpmRoot/$pfxPath", 
	  "LSDYc", 0,
	  "${lfn4}cYYYY", "",
	  "BLOB");

XcuteComm("./gfal_test",
	  "-g 4 -D $tempDir -R -W $finit4 $srm4v2", 
	  "GFALd", 0,
	  "srm_get: 3", "",
	  "surl: 3");
XcuteComm("dpns-ls -il",
	  "$dpmRoot/$pfxPath", 
	  "LSDYd", 0,
	  "${lfn4}dYY", "",
	  "BLOB");

## Temporarily (29/03/07) ... Removed 30/03/07.
if ( $mach eq 'lxb1903' ) {
####    exit 0;
}

###goto EXITE;
####exit 0;

## srmv1 tests ...
##Cchdir "/afs/cern.ch/project/gd/grodid/SLC3-CVS-dpm-133-n/LCG-DM/test/srmv1";

## rfio
XcuteComm("srmv1Suite",
	  "$fmach $user rfio $sfile $pfxPath", 
	  "SV1R", 0,
	  "Final result:", "PASSED",
	  "SURL:");
(my $srm5 = $result) =~ s/_FILX/_FILE/;
@m = split /\//, $srm5;
my $lfn5 = $m[-1];

## gsiftp
XcuteComm("srmv1Suite",
	  "$fmach $user gsiftp $sfile $pfxPath", 
	  "SV1F", 0,
	  "Final result:", "PASSED",
	  "SURL:");
(my $srm6 = $result) =~ s/_FILX/_FILE/;
@m = split /\//, $srm6;
my $lfn6 = $m[-1];

## Crosscheck ...
XcuteComm("dpns-ls -il",
	  "$dpmRoot/$pfxPath | grep \"`date '+%b %d'`\" ", 
	  "LSD6", 0,
	  "${lfn6}", "",
	  "BLOB");

$srm4Y =~ s/8446/8443/;;
## srm_testget on one of the files created by the Gfal test ($srm4Y)
XcuteComm("srm_testget",
	  "$srm4Y", 
	  "STGTa", 0,
	  "request state", "$statDone",
	  "TURL =");
my $turl7 = $result;

### This one postponed ...
### $srm4Y =~ s;:8443/;/srm/managerv1?SFN=; ;;
### XcuteComm("srm_testget",
### 	  "$srm4Y", 
### 	  "STGTb", 0,
### 	  "request state", "$statDone",
### 	  "TURL =");

## srmv2 tests ...
##Cchdir "/afs/cern.ch/project/gd/grodid/SLC3-CVS-dpm-133-n/LCG-DM/test/srmv2";
##??chdir "$relPath/test/srmv2";

## srmv2Suite
XcuteComm("srmv2Suite",
	  "$fmach $user $sfile $pfxPath", 
	  "SRV2", 0,
	  "OVERALL SUITE =", "[OK]",
	  "BLOB");
@m = grep /GID4:.*?Done OK/, @res;
@m = split /\s+/, $m[0];
print " srm8: $m[1]\n";
(my $srm8 = $m[1]) =~ s/8444/8443/;;

##"RSP: soap_call_ns1__srmReserveSpace returned s_token:"
my $s_token = XtractVal("RSP2: soap_call_ns1__srmReserveSpace returned s_token:");
print " DPMSTOKEN: $s_token\n";

## socket tests ...
##Cchdir "/afs/cern.ch/project/gd/grodid/SLC3-CVS-dpm-133-n/LCG-DM/test/dpm";
##??chdir "$relPath/test/dpm";

## socket
XcuteComm("socketSuite",
	  "$fmach $user $sfile $pfxPath $s_token", 
	  "SOCK", 0,
	  "OVERALL SUITE =", "[OK]",
	  "BLOB");
@m = grep /GID3:.*?Done OK/, @res;
@m = split /\s+/, $m[0];
print " srm9: $m[1]\n";
my $srm9 = $m[1];
$srm9 = "srm://$fmach:8443/$srm9";
@m = split /\//, $srm9;
my $lfn9 = $m[-1];

## srm tests ...
##Cchdir "/afs/cern.ch/project/gd/grodid/SLC3-CVS-dpm-133-n/LCG-DM/test/srmv1";
chdir "$tempDir";

## srm_testget on one of the files created by the srmv2 test ($srm8)
XcuteComm("srm_testget",
	  "$srm8", 
	  "TGT8", 0,
	  "request state", "$statDone",
	  "TURL =");
my $turl8 = $result;

## srm_testget on one of the files created by the socket test ($srm9)
XcuteComm("srm_testget",
	  "$srm9", 
	  "TGT9", 0,
	  "request state", "$statDone",
	  "TURL =");
my $turl9 = $result;

$ENV{PATH} = "$relPath/test/srmv2.2:$ENV{PATH}";
## srmv2.2Suite
XcuteComm("srmv2Suite",
	  "$fmach 8446 $user $sfile $choiceVO $pfxPath", 
	  "SRV22", 0,
	  "OVERALL SUITE =", "[OK]",
	  'BRGrf: state\[0\] = 0, SRM_SUCCESS, SURL =');
##OLD	  "SURL =");

# @m = grep /GID4:.*?Done OK/, @res;
# @m = split /\s+/, $m[0];
print " srm10: $result\n";
(my $srm10 = $result) =~ s/8446/8443/;;
@m = split /\//, $srm10;
my $lfn10 = $m[-1];

## srm_testget on one of the files created by the srv2.2 test ($srm10)
XcuteComm("srm_testget",
	  "$srm10", 
	  "TGT10", 0,
	  "request state", "$statDone",
	  "TURL =");
my $turl10 = $result;

## Crosscheck ...
XcuteComm("dpns-ls -il",
	  "$dpmRoot/$pfxPath | grep \"`date '+%b %d'`\" ", 
	  "LSD10", 0,
	  "${lfn10}_R3b", "",
	  "BLOB");

if (0) {
XcuteComm("dpns-ls -il",
	  "$dpmRoot/$pfxPath | grep \"`date '+%b %d'`\" ", 
	  "LSD10_b", 0,
	  "${lfn10}".'\$', "",
	  "BLOB");

XcuteComm("dpns-ls -il",
	  "$dpmRoot/$pfxPath | grep \"`date '+%b %d'`\" ", 
	  "LSD10_c", 0,
	  "${lfn10}\n", "",
	  "BLOB");
}

print "\n";
print " turl7: $turl7 \n";
print " turl8: $turl8 \n";
print " turl9: $turl9 \n";
print " turl10: $turl10 \n";

system("ls -l $tempDir");
system("which srm_testget");

# print " OVERALL Score: OK=$globOK FAILED=$globFD\n";
##my $flat = "@res";
# my @m = split /\s+/, $flat;
# my $pool = XtractVal("POOL");
# print " M: ", scalar(@m), " $m[-1] $pool\n";

# if (0) {
# XcuteComm("dpns-ls -ld",
# 	  "$dpmRoot/$pfxPath", "LSD", "BLOB", 0);

# XcuteComm("dpns-ls -l",
# 	  "$dpmRoot/$pfxPath", "LSL", "BLOB", 0);

# my $finit1 = "$ENV{PWD}/gilb-OLD";
# my $lfn1   = "ggtglob$sfile";
# XcuteComm("lcg-cr",
# 	  "-v --vo dteam -d $fmach -l lfn:$lfn1 -P $pfxPath/$lfn1 file:$finit1",
# 	  "LCR", 0,
# 	  "Alias registered in Catalog:", "lfn:$lfn1",
# 	  "Destination URL registered in Catalog:")
# }

EXITE:

print " OVERALL Score: OK=$globOK FAILED=$globFD\n";
## Keep it to the bottom ...
restoreStdouterr($fhlRef);
print " OVERALL Score: OK=$globOK FAILED=$globFD\n";
print " Log File available in: $logFile\n";

exit 0;

####################################################################################################
sub XcuteComm {

    $operation = shift;
    my $cargs = shift;
    my $label = shift;
    my $fatalXit  = shift;
    my $trigStat = shift;
    my $xpectStat = shift;
    my $trigRslt = shift;
    if ( ! $statusLocal && "$trigStat" ne "BLOCK") { $xCount++; }

    my $filter = "| perl -pe 's/\\s+\\d+ bytes.*sec inst//'";

    $status = "[UNDEF]";
    $result = " ";
    @res = ();

    $command = "$operation $cargs";

    my $keyP = '++++';
    my $keyS = 'STEP';
    my $keyO = 'Operation';
    my $keyR = 'Result';
    if ( $statusLocal ) {
	$keyP .= '0';
	$keyS .= '0';
	$keyO .= '0';
	$keyR .= '0';
    }
    if ( "$trigStat" eq "BLOCK" ) {
	$keyP .= 'H';
	$keyS .= 'H';
	$keyO .= 'H';
	$keyR .= 'H';
    }

    chomp($dateST = `date '+%y%m%d-%H%M%S'`);
    print "\n$keyP $$ $dateST\n";
    print " ${keyS}: $xCount OPERATION: $operation CMD: $command\n";

    my $tStart;
    my $tEnd;
    my $tElapse;
    if ( ! $ENV{DPM_TESTAREA} ) {
	## Normal case ...
	$tStart = time();
	if ( $operation eq "lcg-cr" ) {
	    open RES, "$command 2>&1 $filter |";
	} else {
	    open RES, "$command 2>&1 |";
	}
	while ( <RES> ) {
	    ## To fit new gridftp reply ...
#	    if ( $_ =~ /^226 Transfer Complete./ ) { $_ = '226 Transfer complete.'; }
##	    $_ =~ s/Transfer Complete/Transfer complete/;
	    if ( ! /^\s+$|^\.\.\.$/ ) {
		print "$label: $_";
	    }
	    push @res, $_;
	}
	$tEnd = time();
	$tElapse = $tEnd - $tStart;
	close RES;
    } else {
	## Called from MainScript ...
	$tStart = time();
	if ( $operation eq "lcg-cr" ) {
	    @res = `$command 2>&1 $filter`;
	} else {
	    @res = `$command 2>&1`;
	}
	$tEnd = time();
	$tElapse = $tEnd - $tStart;
	foreach ( @res ) {
	    if ( ! /^\s+$|^\.\.\.$/ ) {
		print "$label: $_";
	    }
	}
    }

    $flat = "@res";
    if ( "$trigStat" eq "EMPTY" ) {
	$status = ( "$flat" eq "" )  ? "[OK]" : "[FAILED]" ;
    } elsif ( "$trigStat" ne "BLOCK" ) {
##	if ( "$xpectStat" ) {
	if ( "$xpectStat" || "YYY$xpectStat" eq "YYY0" ) {
	    $status = ( "XXX$xpectStat" eq "XXX".XtractVal($trigStat) ) ? "[OK]" : "[FAILED]" ;
	} else {
	    $status = ( XtractVal($trigStat) ) ? "[OK]" : "[FAILED]" ;
	}
    }

    if ( "$trigRslt" ne "BLOB" ) {
	$result = XtractVal($trigRslt);
	if ( $operation eq "lcg-cr" && $result eq "" ) {
	    $status = "[FAILED]";
	}
    }

    if ( ! $statusLocal ) {
	if ( $status eq "[OK]" ) { $globOK++; }
	if ( $status eq "[FAILED]" ) { $globFD++; }
    } else {
	if ( $status eq "[FAILED]" ) { $statusLocal = "[FAILED]"; }
    }

    if ( $status ne "[OK]" && $fatalXit) {
	foreach ( @res ) {
	    print " FAILURE: $_";
	}
	exit 1;
    } else {
	my $operationP = "$operation";
	if ( $label eq 'SRV22' && $operationP eq 'srmv2Suite' ) { $operationP = 'srmv22Suite'; }
	print " ${keyO}: $operationP = $status Duration: $tElapse sec.\n";
	print "<_________________________________________________________________________>\n\n";
    }

    print " ${keyR}: $result Status: $status\n";
#   print " Result: $result Status: $status -- $xCount $globOK $globFD\n";

    return 0;  ##  ($result, $status);

}

####################################################################################################
sub XcuteCommGOOD {

    $operation = shift;
    my $cargs = shift;
    my $label = shift;
    my $fatalXit  = shift;
    my $trigStat = shift;
    my $xpectStat = shift;
    my $trigRslt = shift;
    if ( ! $statusLocal ) { $xCount++; }

    my $filter = "| perl -pe 's/\\s+\\d+ bytes.*sec inst//'";

    ##OLDundef $status;
    $status = "[UNDEF]";
    $result = " ";
    @res = ();
    ##$usage = `$operation 2>&1`;
    $command = "$operation $cargs";
  chomp($dateST = `date '+%y%m%d-%H%M%S'`);
  print "\n++++ $$ $dateST\n";
    ##OLDprint " STEP: $xCount OPERATION: $operation USAGE: $usage CMD: $command\n";
    print " STEP: $xCount OPERATION: $operation CMD: $command\n";

    my $tStart = time();
    if ( $operation eq "lcg-cr" ) { @res = `$command 2>&1 $filter`; }
    else { @res = `$command 2>&1`; }
    my $tEnd = time();
    my $tElapse = $tEnd - $tStart;
##    my $exitFlag = 0;
    foreach ( @res ) {
	##OLD$_ =~ s/req.*TURL/TURL/;
	if ( ! /^\s+$|^\.\.\.$/ ) { print "$label: $_"; }
	if (0) {
	my @m = split;
	if ( /$trigStat/ ) {
	    $status = ( "$xpectStat" eq "$m[-1]" ) ? "[OK]" : "[FAILED]" ;
	}
	if ( /$trigRslt/ ) {
	    $result = $m[-1];
	}
    }
    }

    $flat = "@res";
##    my $lstat = XtractVal($trigStat);
##    $status = ( "$xpectStat" eq "$lstat" ) ? "[OK]" : "[FAILED]" ;
    if ( "$trigStat" eq "EMPTY" ) {
##	$status = ( "$res[0]" eq "" )  ? "[OK]" : "[FAILED]" ;
	$status = ( "$flat" eq "" )  ? "[OK]" : "[FAILED]" ;
    } elsif ( "$trigStat" ne "BLOCK" ) {
	if ( "$xpectStat" ) {
	    $status = ( "$xpectStat" eq XtractVal($trigStat) ) ? "[OK]" : "[FAILED]" ;
	} else {
	    $status = ( XtractVal($trigStat) ) ? "[OK]" : "[FAILED]" ;
	}
    }

    if ( "$trigRslt" ne "BLOB" ) {
	$result = XtractVal($trigRslt);
    }

    if ( ! $statusLocal ) {
	if ( $status eq "[OK]" ) { $globOK++; }
	if ( $status eq "[FAILED]" ) { $globFD++; }
    } else {
	if ( $status eq "[FAILED]" ) { $statusLocal = "[FAILED]"; }
    }

    if ( $status ne "[OK]" && $fatalXit) {
	foreach ( @res ) {
	    print " FAILURE: $_";
	}
	exit 1;
    } else {
	print " Operation: $operation = $status Duration: $tElapse sec.\n";
	print "<_________________________________________________________________________>\n\n";
    }

    print " Result: $result Status: $status\n";
#   print " Result: $result Status: $status -- $xCount $globOK $globFD\n";

    return 0;  ##  ($result, $status);

}

####################################################################################################
sub XcuteCommOLD {

    $operation = shift;
    my $cargs = shift;
    my $label = shift;
    my $xpectStat = shift;
    my $fatalXit  = shift;
    $xCount++;

    undef $status;
    @res = ();
    ##$usage = `$operation 2>&1`;
    $command = "$operation $cargs";
  chomp($dateST = `date '+%y%m%d-%H%M%S'`);
  print "\n++++ $$ $dateST\n";
    ##print " STEP: $xCount OPERATION: $operation USAGE: $usage CMD: $command\n";
    print " STEP: $xCount OPERATION: $operation CMD: $command\n";
    my $tStart = time();
    @res = `$command 2>&1`;
    my $tEnd = time();
    my $tElapse = $tEnd - $tStart;
##    my $exitFlag = 0;
    foreach ( @res ) {
	$_ =~ s/req.*TURL/TURL/;
	if ( ! /^\s+$|^\.\.\.$/ ) { print "$label: $_"; }
	my @m = split;
	if ( /request state/ ) {
	    $status = ( "$xpectStat" eq "$m[2]" ) ? "[OK]" : "[FAILED]" ;
	}
    }
    if ( $status ne "[OK]" && $fatalXit) {
	foreach ( @res ) {
	    print " FAILURE: $_";
	}
	exit 1;
    } else {
	print " Operation: $operation = $status Duration: $tElapse \n";
	print "<_________________________________________________________________________>\n\n";
    }

    return 0;

}

####################################################################################################
# Same as above, but requires that the proxy will still be valid
# for the duration (hours) provided as 1st arg (def: 1 hour)
sub checkProxyTime {
    my $time = shift;
#    if ( $time eq "" ) { $time = 1; }
    $time ||= 1;
    my $trash = `grid-proxy-info -exists -h $time `;
    my $rc = $?;
    return $rc;
}

####################################################################################################
# A utility to temporarily switch the STDOUT and STDERR to a file
sub switchStdouterr {
    local *SAVEOUT;
    local *SAVEERR;
    my ($file) = @_;
#p    print " Sending STDOUT to $file \n";
    open SAVEOUT, ">&STDOUT" ;
    open SAVEERR, ">&STDERR" ;
    open STDOUT, ">$file" or die "Can't redirect STDOUT \n";
    open STDERR, ">&STDOUT" or die "Can't dup STDOUT \n";
    select STDERR; $|=1;
    select STDOUT; $|=1;
    my @fhl = (*SAVEOUT, *SAVEERR);
    return \@fhl;
}

####################################################################################################
# A utility to restore the STDOUT and STDERR to their initial state
sub restoreStdouterr {
    local *SAVEOUT;
    local *SAVEERR;
#    (*FH) = @_;
    my ($arrayref) = @_;
    (*SAVEOUT, *SAVEERR) = @$arrayref;
    close STDOUT;
    close STDERR;
    open STDOUT, ">&SAVEOUT";
    open STDERR, ">&SAVEERR";
}

####################################################################################################
sub RemCols {
    foreach my $n (0 .. $#res) {
      $res[$n] =~ s/\s+:/:/g;
##    print " RemCols:: >>$res[$n]<< \n";
    }
}

####################################################################################################
sub RemDots {
    foreach my $n (0 .. $#res) {
      $res[$n] =~ s/\.{2,}//g;
##    print " RemDots:: >>$res[$n]<< \n";
    }
}

####################################################################################################
sub dicomTests {
##dpm/dpm-register --user '/DC=org/DC=doegrids/OU=People/CN=Gilbert Grosdidier 378567' --filesize 641 --server `hostname --fqdn` --group dteam --status N --pfn dicom:///tmp/grodid/dicom_testgg_sleep_10.008 /dpm/cern.ch/home/dteam/grodid/tglob/Mlxb5407/dicom-tgg.013
##rfio/rfdir /dpm/cern.ch/home/dteam/grodid/tglob/Mlxb5407 | grep dicom
##rfio/rfcp /dpm/cern.ch/home/dteam/grodid/tglob/Mlxb5407/dicom-tgg.013 /var/tmp/grodid/global/lxb5407/2007-12-22/fil140003/dicom-tgg.007r
    chomp(my $currSubject = `voms-proxy-info -identity`);

    if (0) {
## Crosscheck ... Template ...
XcuteComm("dpns-ls -il",
	  "$dpmRoot/$pfxPath | grep \"`date '+%b %d'`\" ", 
	  "LSD10", 0,
	  "${lfn10}_R3b", "",
	  "BLOB");
}

## Creation of dicom files ...
    my $dicomR = "dicom_testgg";
    my $dicomS = "dicom_testgg_sleep_";
    my $dicom1 = "$tempDir/${dicomR}.001";
    my $dicom2 = "$tempDir/${dicomR}.002";
    my $dicom3 = "$tempDir/${dicomR}.003";
    my $dicom10 = "$tempDir/${dicomR}.010";
    my $dicom12 = "$tempDir/${dicomR}.012";
    my $dicom14 = "$tempDir/${dicomR}.014";
    system("cp -p $finit1 $dicom1");
    system("cp -p $finit1 $dicom2");
    system("cp -p $finit1 $dicom3");
    system("cp -p $finit1 $dicom10");
    system("cp -p $finit1 $dicom12");
    system("cp -p $finit1 $dicom14");
## with sleep option
    my $dicoms20 = "$tempDir/${dicomS}20.004";
    my $dicoms40 = "$tempDir/${dicomS}40.005";
    my $dicoms26 = "$tempDir/${dicomS}20.006";
    my $dicoms47 = "$tempDir/${dicomS}40.007";
    my $dicoms28 = "$tempDir/${dicomS}20.008";
    my $dicoms49 = "$tempDir/${dicomS}40.009";
    my $dicoms21 = "$tempDir/${dicomS}20.021";
    my $dicoms23 = "$tempDir/${dicomS}20.023";
    my $dicoms25 = "$tempDir/${dicomS}20.025";
    system("cp -p $finit1 $dicoms20");
    system("cp -p $finit1 $dicoms40");
    system("cp -p $finit1 $dicoms26");
    system("cp -p $finit1 $dicoms47");
    system("cp -p $finit1 $dicoms28");
    system("cp -p $finit1 $dicoms49");
    system("cp -p $finit1 $dicoms21");
    system("cp -p $finit1 $dicoms23");
    system("cp -p $finit1 $dicoms25");
    my @m = split /\s+/, `ls -l $finit1`;
## Registration ...
    XcuteComm("rfmkdir",
	      "-m 755 -p $fmach:/tmp/$pfxPath", 
	      "DICM01", 0,
	      "EMPTY", "",
	      "BLOB");

## R001
    XcuteComm("rfcp",
	      "$tempDir/${dicomR}.001 $fmach:/tmp/$pfxPath/${dicomR}.001",
	      "DICC01", 1,
	      "seconds through local", "",
	      "BLOB");

##	      "--user \"${currSubject}\" --filesize $m[4] --server $fmach --group $choiceVO --status N --pfn dicom:///tmp/$pfxPath/${dicomR}.001 $dpmRoot/$pfxPath/${dicomR}.001",
##	      "--user \"${currSubject}\" --filesize $m[4] --server $fmach --group \'dteam/Role=operator\' --status N --pfn dicom:///tmp/$pfxPath/${dicomR}.001 $dpmRoot/$pfxPath/${dicomR}.001",
    XcuteComm("dpm-register",
	      "--filesize $m[4] --server $fmach --status N --pfn dicom:///tmp/$pfxPath/${dicomR}.001 $dpmRoot/$pfxPath/${dicomR}.001",
	      "DICR01", 0,
	      "EMPTY", "",
	      "BLOB");
    XcuteComm("rfdir",
	      "$dpmRoot/$pfxPath | grep dicom",
	      "DICP01", 0,
	      "${dicomR}.001", "",
	      "BLOB");

## R002
    XcuteComm("rfcp",
	      "$tempDir/${dicomR}.002 $fmach:/tmp/$pfxPath/${dicomR}.002",
	      "DICC02", 1,
	      "seconds through local", "",
	      "BLOB");
    XcuteComm("dpm-register",
	      "--filesize $m[4] --server $fmach --status N --pfn dicom:///tmp/$pfxPath/${dicomR}.002 $dpmRoot/$pfxPath/${dicomR}.002",
	      "DICR02", 0,
	      "EMPTY", "",
	      "BLOB");
    XcuteComm("rfdir",
	      "$dpmRoot/$pfxPath | grep dicom",
	      "DICP02", 0,
	      "${dicomR}.002", "",
	      "BLOB");

## R003
    XcuteComm("rfcp",
	      "$tempDir/${dicomR}.003 $fmach:/tmp/$pfxPath/${dicomR}.003",
	      "DICC03", 1,
	      "seconds through local", "",
	      "BLOB");
    XcuteComm("dpm-register",
	      "--filesize $m[4] --server $fmach --status N --pfn dicom:///tmp/$pfxPath/${dicomR}.003 $dpmRoot/$pfxPath/${dicomR}.003",
	      "DICR03", 0,
	      "EMPTY", "",
	      "BLOB");
    XcuteComm("rfdir",
	      "$dpmRoot/$pfxPath | grep dicom",
	      "DICP03", 0,
	      "${dicomR}.003", "",
	      "BLOB");

    ## Get the file and wait for it
if (0) {
    XcuteComm("rfcp",
	      "$dpmRoot/$pfxPath/${dicomR}.001 $tempDir/${dicomR}.001r",
	      "DICF01", 1,
	      "seconds through eth", "",
	      "BLOB");
}

    ## File with 20s delay ...
## S020
    XcuteComm("rfcp",
	      "$tempDir/${dicomS}20.004 $fmach:/tmp/$pfxPath/${dicomS}20.004",
	      "DICC04", 1,
	      "seconds through local", "",
	      "BLOB");
##	      "--user \"${currSubject}\" --filesize $m[4] --server $fmach --group $choiceVO --status N --pfn dicom:///tmp/$pfxPath/${dicomS}20.004 $dpmRoot/$pfxPath/${dicomS}20.004",
    XcuteComm("dpm-register",
	      "--filesize $m[4] --server $fmach --status N --pfn dicom:///tmp/$pfxPath/${dicomS}20.004 $dpmRoot/$pfxPath/${dicomS}20.004",
	      "DICR04", 0,
	      "EMPTY", "",
	      "BLOB");
    XcuteComm("rfdir",
	      "$dpmRoot/$pfxPath | grep dicom",
	      "DICP04", 0,
	      "${dicomS}20.004", "",
	      "BLOB");

## S026
    XcuteComm("rfcp",
	      "$tempDir/${dicomS}20.006 $fmach:/tmp/$pfxPath/${dicomS}20.006",
	      "DICC06", 1,
	      "seconds through local", "",
	      "BLOB");
    XcuteComm("dpm-register",
	      "--filesize $m[4] --server $fmach --status N --pfn dicom:///tmp/$pfxPath/${dicomS}20.006 $dpmRoot/$pfxPath/${dicomS}20.006",
	      "DICR06", 0,
	      "EMPTY", "",
	      "BLOB");
    XcuteComm("rfdir",
	      "$dpmRoot/$pfxPath | grep dicom",
	      "DICP06", 0,
	      "${dicomS}20.006", "",
	      "BLOB");

## S028
    XcuteComm("rfcp",
	      "$tempDir/${dicomS}20.004 $fmach:/tmp/$pfxPath/${dicomS}20.008",
	      "DICC08", 1,
	      "seconds through local", "",
	      "BLOB");
    XcuteComm("dpm-register",
	      "--filesize $m[4] --server $fmach --status N --pfn dicom:///tmp/$pfxPath/${dicomS}20.008 $dpmRoot/$pfxPath/${dicomS}20.008",
	      "DICR08", 0,
	      "EMPTY", "",
	      "BLOB");
    XcuteComm("rfdir",
	      "$dpmRoot/$pfxPath | grep dicom",
	      "DICP08", 0,
	      "${dicomS}20.008", "",
	      "BLOB");

if (0) {
    ## Get the file and DON'T wait for it
    system("rfcp $dpmRoot/$pfxPath/${dicomS}20.004 $tempDir/${dicomS}20.004r &");
    ## Cross-check ...
    system("ls -l $tempDir/${dicomS}20.004r");
}

    ## uses srmv1 ...
    if (0) {
    XcuteComm("srm_testget",
	      "srm://${fmach}:8443/$dpmRoot/$pfxPath/${dicomS}20.004", 
	      "DICS04", 0,
	      "request state", "",
	      "BLOB");
    XcuteComm("srm_testget",
	      "srm://${fmach}:8443/$dpmRoot/$pfxPath/${dicomR}.001", 
	      "DICS01", 0,
	      "request state", "",
	      "BLOB");
}

    ## Work with srmv1 ... ..................................................................................

    ## Get both files and wait ... (all Nearline)
    XcuteComm("srm_testget",
	      "srm://${fmach}:8443/$dpmRoot/$pfxPath/${dicomS}20.008 srm://${fmach}:8443/$dpmRoot/$pfxPath/${dicomR}.003", 
	      "DICG0R3", 0,
	      "request state", "Ready",
	      "BLOB");
    sleep 5;

    ## File with 40s delay ...
    XcuteComm("rfcp",
	      "$tempDir/${dicomS}40.009 $fmach:/tmp/$pfxPath/${dicomS}40.009",
	      "DICC09", 1,
	      "seconds through local", "",
	      "BLOB");
    XcuteComm("dpm-register",
	      "--filesize $m[4] --server $fmach --status N --pfn dicom:///tmp/$pfxPath/${dicomS}40.009 $dpmRoot/$pfxPath/${dicomS}40.009",
	      "DICR09", 0,
	      "EMPTY", "",
	      "BLOB");
    XcuteComm("rfdir",
	      "$dpmRoot/$pfxPath | grep dicom",
	      "DICP09", 0,
	      "${dicomS}40.009", "",
	      "BLOB");


    ## Get 3 files and wait ... (one Nearline)
    XcuteComm("srm_testget",
	      "srm://${fmach}:8443/$dpmRoot/$pfxPath/${dicomS}20.008 srm://${fmach}:8443/$dpmRoot/$pfxPath/${dicomR}.003 srm://${fmach}:8443/$dpmRoot/$pfxPath/${dicomS}40.009", 
	      "DICG09", 0,
	      "request state", "Ready",
	      "BLOB");
    sleep 15;

    ## Get 3 files and wait again ... (all Online already)
    XcuteComm("srm_testget",
	      "srm://${fmach}:8443/$dpmRoot/$pfxPath/${dicomS}20.008 srm://${fmach}:8443/$dpmRoot/$pfxPath/${dicomR}.003 srm://${fmach}:8443/$dpmRoot/$pfxPath/${dicomS}40.009", 
	      "DICG03", 0,
	      "request state", "Ready",
	      "BLOB");

    ## Get 3 files and wait (3rd time) ... (all Online already)
    sleep 15;
    XcuteComm("srm_testget",
	      "srm://${fmach}:8443/$dpmRoot/$pfxPath/${dicomS}20.008 srm://${fmach}:8443/$dpmRoot/$pfxPath/${dicomR}.003 srm://${fmach}:8443/$dpmRoot/$pfxPath/${dicomS}40.009", 
	      "DICG04", 0,
	      "request state", "Ready",
	      "BLOB");

    ## Work with srmv2 ... ..................................................................................

    ## Get both files and wait ... (all Nearline)
    XcuteComm("srm2_testGet",
	      "gsiftp - srm://${fmach}:8444/$dpmRoot/$pfxPath/${dicomS}20.006 srm://${fmach}:8444/$dpmRoot/$pfxPath/${dicomR}.002", 
	      "DICG0R2", 0,
	      "request state", "0",
	      "BLOB");
    sleep 5;

    ## File with 40s delay ...
    XcuteComm("rfcp",
	      "$tempDir/${dicomS}40.007 $fmach:/tmp/$pfxPath/${dicomS}40.007",
	      "DICC07", 1,
	      "seconds through local", "",
	      "BLOB");
    XcuteComm("dpm-register",
	      "--filesize $m[4] --server $fmach --status N --pfn dicom:///tmp/$pfxPath/${dicomS}40.007 $dpmRoot/$pfxPath/${dicomS}40.007",
	      "DICR07", 0,
	      "EMPTY", "",
	      "BLOB");
    XcuteComm("rfdir",
	      "$dpmRoot/$pfxPath | grep dicom",
	      "DICP07", 0,
	      "${dicomS}40.007", "",
	      "BLOB");


    ## Get 3 files and wait ... (one Nearline)
    XcuteComm("srm2_testGet",
	      "gsiftp - srm://${fmach}:8444/$dpmRoot/$pfxPath/${dicomS}20.006 srm://${fmach}:8444/$dpmRoot/$pfxPath/${dicomR}.002 srm://${fmach}:8444/$dpmRoot/$pfxPath/${dicomS}40.007", 
	      "DICG07", 0,
	      "request state", "0",
	      "BLOB");
    sleep 15;

    ## Get 3 files and wait again ... (all Online already)
    XcuteComm("srm2_testGet",
	      "rfio - srm://${fmach}:8444/$dpmRoot/$pfxPath/${dicomS}20.006 srm://${fmach}:8444/$dpmRoot/$pfxPath/${dicomR}.002 srm://${fmach}:8444/$dpmRoot/$pfxPath/${dicomS}40.007", 
	      "DICG03", 0,
	      "request state", "0",
	      "BLOB");

    ## Get 3 files and wait (3rd time) ... (all Online already) ... 
    sleep 15;
    XcuteComm("srm2_testGet",
	      "rfio - srm://${fmach}:8444/$dpmRoot/$pfxPath/${dicomS}20.006 srm://${fmach}:8444/$dpmRoot/$pfxPath/${dicomR}.002 srm://${fmach}:8444/$dpmRoot/$pfxPath/${dicomS}40.007", 
	      "DICG04", 0,
	      "request state", "0",
	      "BLOB");

    ## Work with srmv2.2 ... .............................................................................
    $ENV{PATH} = "$relPath/test/srmv2.2:$ENV{PATH}";

    ## Get both files and wait ... (all Nearline)
    XcuteComm("srm2_testGet",
	      "gsiftp - 25 srm://${fmach}:8446/$dpmRoot/$pfxPath/${dicomS}20.004 srm://${fmach}:8446/$dpmRoot/$pfxPath/${dicomR}.001", 
	      "DICG01", 0,
	      "request state", "0",
	      "BLOB");
    sleep 5;

    ## File with 40s delay ...
    XcuteComm("rfcp",
	      "$tempDir/${dicomS}40.005 $fmach:/tmp/$pfxPath/${dicomS}40.005",
	      "DICC05", 1,
	      "seconds through local", "",
	      "BLOB");
##	      "--user \"${currSubject}\" --filesize $m[4] --server $fmach --group $choiceVO --status N --pfn dicom:///tmp/$pfxPath/${dicomS}40.005 $dpmRoot/$pfxPath/${dicomS}40.005",
    XcuteComm("dpm-register",
	      "--filesize $m[4] --server $fmach --status N --pfn dicom:///tmp/$pfxPath/${dicomS}40.005 $dpmRoot/$pfxPath/${dicomS}40.005",
	      "DICR05", 0,
	      "EMPTY", "",
	      "BLOB");
    XcuteComm("rfdir",
	      "$dpmRoot/$pfxPath | grep dicom",
	      "DICP05", 0,
	      "${dicomS}40.005", "",
	      "BLOB");


    ## Get 3 files and wait ... (one Nearline)
    XcuteComm("srm2_testGet",
	      "gsiftp - 55 srm://${fmach}:8446/$dpmRoot/$pfxPath/${dicomS}20.004 srm://${fmach}:8446/$dpmRoot/$pfxPath/${dicomR}.001 srm://${fmach}:8446/$dpmRoot/$pfxPath/${dicomS}40.005", 
	      "DICG02", 0,
	      "request state", "0",
	      "BLOB");
    sleep 15;

    ## Get 3 files and wait again ... (all Online already)
    XcuteComm("srm2_testGet",
	      "rfio - 10 srm://${fmach}:8446/$dpmRoot/$pfxPath/${dicomS}20.004 srm://${fmach}:8446/$dpmRoot/$pfxPath/${dicomR}.001 srm://${fmach}:8446/$dpmRoot/$pfxPath/${dicomS}40.005", 
	      "DICG03", 0,
	      "request state", "0",
	      "BLOB");

    ## Get 3 files and wait (3rd time) ... (all Online already)
    sleep 15;
    XcuteComm("srm2_testGet",
	      "rfio - 1 srm://${fmach}:8446/$dpmRoot/$pfxPath/${dicomS}20.004 srm://${fmach}:8446/$dpmRoot/$pfxPath/${dicomR}.001 srm://${fmach}:8446/$dpmRoot/$pfxPath/${dicomS}40.005", 
	      "DICG04", 0,
	      "request state", "0",
	      "BLOB");

## AbortRequest + AbortFiles sequence ... under srmv2.2

## R010
    XcuteComm("rfcp",
	      "$tempDir/${dicomR}.010 $fmach:/tmp/$pfxPath/${dicomR}.010",
	      "DICC10", 1,
	      "seconds through local", "",
	      "BLOB");
    XcuteComm("dpm-register",
	      "--filesize $m[4] --server $fmach --status N --pfn dicom:///tmp/$pfxPath/${dicomR}.010 $dpmRoot/$pfxPath/${dicomR}.010",
	      "DICR10", 0,
	      "EMPTY", "",
	      "BLOB");
    XcuteComm("rfdir",
	      "$dpmRoot/$pfxPath | grep dicom",
	      "DICP10", 0,
	      "${dicomR}.010", "",
	      "BLOB");

## S021
    XcuteComm("rfcp",
	      "$tempDir/${dicomS}20.021 $fmach:/tmp/$pfxPath/${dicomS}20.021",
	      "DICC21", 1,
	      "seconds through local", "",
	      "BLOB");
    XcuteComm("dpm-register",
	      "--filesize $m[4] --server $fmach --status N --pfn dicom:///tmp/$pfxPath/${dicomS}20.021 $dpmRoot/$pfxPath/${dicomS}20.021",
	      "DICR21", 0,
	      "EMPTY", "",
	      "BLOB");
    XcuteComm("rfdir",
	      "$dpmRoot/$pfxPath | grep dicom",
	      "DICP21", 0,
	      "${dicomS}20.021", "",
	      "BLOB");

    my $stat26 = 0;
    my $endPoint = "srm://${fmach}:8446";
## The '+' after 'gsiftp' is to indicate that testGet must NOT wait for the PTGet operation to complete
    XcuteComm("srm2_testGet",
	      "gsiftp + - srm://${fmach}:8446/$dpmRoot/$pfxPath/${dicomS}20.021 srm://${fmach}:8446/$dpmRoot/$pfxPath/${dicomR}.010",
	      "DICTARa", 0,
	      'pstate\[1\] =', '17,',
	      "BLOB");
my $gr_token = XtractVal('r_token');

    XcuteComm("srm2_testGetRequestStatus",
	      "$endPoint $gr_token",
	      "DICTARb", 0, 
	      'state\[0\] =', '18,',
	      "BLOB");
##$status = ( XtractVal('state\[0\]:') eq "$stat26" ) ? '[OK]' : '[FAILED]';
##if ( $status ne '[OK]' ) { &printAndCExit(); }

    XcuteComm("srm2_testAbortRequest",
	      "$endPoint $gr_token",
	      "DICTARar", 0, 
	      "request state", "0",
	      "BLOB");

    XcuteComm("srm2_testGetRequestStatus",
	      "$endPoint $gr_token",
	      "DICTARd", 0, 
	      "request getstate", "20",
	      "BLOB");
$status = ( XtractVal('state\[0\]:') eq '20' ) ? '[OK]' : '[FAILED]';
##if ( $status ne '[OK]' ) { &printAndCExit(); }

## R012
    XcuteComm("rfcp",
	      "$tempDir/${dicomR}.012 $fmach:/tmp/$pfxPath/${dicomR}.012",
	      "DICC12", 1,
	      "seconds through local", "",
	      "BLOB");
    XcuteComm("dpm-register",
	      "--filesize $m[4] --server $fmach --status N --pfn dicom:///tmp/$pfxPath/${dicomR}.012 $dpmRoot/$pfxPath/${dicomR}.012",
	      "DICR12", 0,
	      "EMPTY", "",
	      "BLOB");
    XcuteComm("rfdir",
	      "$dpmRoot/$pfxPath | grep dicom",
	      "DICP12", 0,
	      "${dicomR}.012", "",
	      "BLOB");

## S023
    XcuteComm("rfcp",
	      "$tempDir/${dicomS}20.023 $fmach:/tmp/$pfxPath/${dicomS}20.023",
	      "DICC23", 1,
	      "seconds through local", "",
	      "BLOB");
    XcuteComm("dpm-register",
	      "--filesize $m[4] --server $fmach --status N --pfn dicom:///tmp/$pfxPath/${dicomS}20.023 $dpmRoot/$pfxPath/${dicomS}20.023",
	      "DICR23", 0,
	      "EMPTY", "",
	      "BLOB");
    XcuteComm("rfdir",
	      "$dpmRoot/$pfxPath | grep dicom",
	      "DICP23", 0,
	      "${dicomS}20.023", "",
	      "BLOB");

    XcuteComm("srm2_testGet",
	      "gsiftp + - srm://${fmach}:8446/$dpmRoot/$pfxPath/${dicomS}20.023 srm://${fmach}:8446/$dpmRoot/$pfxPath/${dicomR}.012",
	      "DICTAFa", 0,
	      'pstate\[1\] =', '17,',
	      "BLOB");
$gr_token = XtractVal('r_token');

    XcuteComm("srm2_testGetRequestStatus",
	      "$endPoint $gr_token",
	      "DICTAFb", 0, 
	      'state\[0\] =', '18,',
	      "BLOB");
##$status = ( XtractVal('state\[0\]:') eq "$stat26" ) ? '[OK]' : '[FAILED]';
##if ( $status ne '[OK]' ) { &printAndCExit(); }

    XcuteComm("srm2_testAbortFiles",
	      "$gr_token srm://${fmach}:8446/$dpmRoot/$pfxPath/${dicomS}20.023 srm://${fmach}:8446/$dpmRoot/$pfxPath/${dicomR}.012",
	      "DICTAFaf", 0, 
	      "request state", "0",
	      "BLOB");

    XcuteComm("srm2_testGetRequestStatus",
	      "$endPoint $gr_token",
	      "DICTAFd", 0, 
	      "request getstate", "20",
	      "BLOB");
$status = ( XtractVal('state\[0\]:') eq '20' ) ? '[OK]' : '[FAILED]';
##if ( $status ne '[OK]' ) { &printAndCExit(); }

## Concurrent get ...

## R014
    XcuteComm("rfcp",
	      "$tempDir/${dicomR}.014 $fmach:/tmp/$pfxPath/${dicomR}.014",
	      "DICC14", 1,
	      "seconds through local", "",
	      "BLOB");
    XcuteComm("dpm-register",
	      "--filesize $m[4] --server $fmach --status N --pfn dicom:///tmp/$pfxPath/${dicomR}.014 $dpmRoot/$pfxPath/${dicomR}.014",
	      "DICR14", 0,
	      "EMPTY", "",
	      "BLOB");
    XcuteComm("rfdir",
	      "$dpmRoot/$pfxPath | grep dicom",
	      "DICP14", 0,
	      "${dicomR}.014", "",
	      "BLOB");

## S025
    XcuteComm("rfcp",
	      "$tempDir/${dicomS}20.025 $fmach:/tmp/$pfxPath/${dicomS}20.025",
	      "DICC25", 1,
	      "seconds through local", "",
	      "BLOB");
    XcuteComm("dpm-register",
	      "--filesize $m[4] --server $fmach --status N --pfn dicom:///tmp/$pfxPath/${dicomS}20.025 $dpmRoot/$pfxPath/${dicomS}20.025",
	      "DICR25", 0,
	      "EMPTY", "",
	      "BLOB");
    XcuteComm("rfdir",
	      "$dpmRoot/$pfxPath | grep dicom",
	      "DICP25", 0,
	      "${dicomS}20.025", "",
	      "BLOB");

    if (0) {
## The '+' after 'gsiftp' is to indicate that testGet must NOT wait for the PTGet operation to complete
    XcuteComm("srm2_testGet",
	      "gsiftp + - srm://${fmach}:8446/$dpmRoot/$pfxPath/${dicomS}20.025 srm://${fmach}:8446/$dpmRoot/$pfxPath/${dicomR}.014",
	      "DICTCGa1", 0,
	      'pstate\[1\] =', '17,',
	      "BLOB");
my $gr1_token = XtractVal('r_token');

    XcuteComm("srm2_testGetRequestStatus",
	      "$endPoint $gr1_token",
	      "DICTCGb1", 0, 
	      'state\[0\] =', '18,',
	      "BLOB");
##$status = ( XtractVal('state\[0\]:') eq "$stat26" ) ? '[OK]' : '[FAILED]';
##if ( $status ne '[OK]' ) { &printAndCExit(); }

    XcuteComm("srm2_testGet",
	      "gsiftp + - srm://${fmach}:8446/$dpmRoot/$pfxPath/${dicomS}20.025 srm://${fmach}:8446/$dpmRoot/$pfxPath/${dicomR}.014",
	      "DICTCGa2", 0,
	      'pstate\[1\] =', '17,',
	      "BLOB");
my $gr2_token = XtractVal('r_token');

    XcuteComm("srm2_testGetRequestStatus",
	      "$endPoint $gr2_token",
	      "DICTCGb2", 0, 
	      'state\[0\] =', '18,',
	      "BLOB");
##$status = ( XtractVal('state\[0\]:') eq "$stat26" ) ? '[OK]' : '[FAILED]';
##if ( $status ne '[OK]' ) { &printAndCExit(); }

    XcuteComm("srm2_testAbortRequest",
	      "$endPoint $gr1_token",
	      "DICTCGar", 0, 
	      "request state", "0",
	      "BLOB");

    XcuteComm("srm2_testGetRequestStatus",
	      "$endPoint $gr1_token",
	      "DICTCGd1", 0, 
	      "request getstate", "20",
	      "BLOB");
$status = ( XtractVal('state\[0\]:') eq '20' ) ? '[OK]' : '[FAILED]';
##if ( $status ne '[OK]' ) { &printAndCExit(); }

    XcuteComm("srm2_testGetRequestStatus",
	      "$endPoint $gr2_token",
	      "DICTCGd2", 0, 
	      "request getstate", "18",
	      "BLOB");
$status = ( XtractVal('state\[0\]:') eq '18' ) ? '[OK]' : '[FAILED]';
##if ( $status ne '[OK]' ) { &printAndCExit(); }

    XcuteComm("srm2_testGet",
	      "gsiftp - 50 srm://${fmach}:8446/$dpmRoot/$pfxPath/${dicomS}20.025 srm://${fmach}:8446/$dpmRoot/$pfxPath/${dicomR}.014",
	      "DICTCGa3", 0,
	      'pstate\[1\] =', '22,',
	      "BLOB");
my $gr3_token = XtractVal('r_token');

    ##sleep(20);
## gr2 should be successful ...
    XcuteComm("srm2_testGetRequestStatus",
	      "$endPoint $gr1_token $gr2_token $gr3_token",
	      "DICTCGe", 0, 
	      "request state", "0",
	      "BLOB");
##$status = ( XtractVal('state\[0\]:') eq '20' ) ? '[OK]' : '[FAILED]';
} else {
## Case with one sleep file only in the PTGet requests ....
## The '+' after 'gsiftp' is to indicate that testGet must NOT wait for the PTGet operation to complete
    XcuteComm("srm2_testGet",
	      "gsiftp + - srm://${fmach}:8446/$dpmRoot/$pfxPath/${dicomS}20.025",
	      "DICTCGa1", 0,
	      'pstate\[0\] =', '17,',
	      "BLOB");
my $gr1_token = XtractVal('r_token');

    XcuteComm("srm2_testGetRequestStatus",
	      "$endPoint $gr1_token",
	      "DICTCGb1", 0, 
	      'state\[0\] =', '18,',
	      "BLOB");
##$status = ( XtractVal('state\[0\]:') eq "$stat26" ) ? '[OK]' : '[FAILED]';
##if ( $status ne '[OK]' ) { &printAndCExit(); }

    XcuteComm("srm2_testGet",
	      "gsiftp + - srm://${fmach}:8446/$dpmRoot/$pfxPath/${dicomS}20.025",
	      "DICTCGa2", 0,
	      'pstate\[0\] =', '17,',
	      "BLOB");
my $gr2_token = XtractVal('r_token');

    XcuteComm("srm2_testGetRequestStatus",
	      "$endPoint $gr2_token",
	      "DICTCGb2", 0, 
	      'state\[0\] =', '18,',
	      "BLOB");
##$status = ( XtractVal('state\[0\]:') eq "$stat26" ) ? '[OK]' : '[FAILED]';
##if ( $status ne '[OK]' ) { &printAndCExit(); }

    if (0) { ## Not any more ...
    XcuteComm("srm2_testAbortRequest",
	      "$endPoint $gr1_token",
	      "DICTCGar", 0, 
	      "request state", "0",
	      "BLOB");
}

    XcuteComm("srm2_testGetRequestStatus",
	      "$endPoint $gr1_token",
	      "DICTCGd1", 0, 
	      "request getstate", "20",
	      "BLOB");
$status = ( XtractVal('state\[0\]:') eq '20' ) ? '[OK]' : '[FAILED]';
##if ( $status ne '[OK]' ) { &printAndCExit(); }

    XcuteComm("srm2_testGetRequestStatus",
	      "$endPoint $gr2_token",
	      "DICTCGd2", 0, 
	      "request getstate", "18",
	      "BLOB");
$status = ( XtractVal('state\[0\]:') eq '18' ) ? '[OK]' : '[FAILED]';
##if ( $status ne '[OK]' ) { &printAndCExit(); }

    XcuteComm("srm2_testGet",
	      "gsiftp - 50 srm://${fmach}:8446/$dpmRoot/$pfxPath/${dicomS}20.025",
	      "DICTCGa3", 0,
	      'pstate\[0\] =', '22,',
	      "BLOB");
my $gr3_token = XtractVal('r_token');

    sleep(20);
## gr2 should be successful ...
    XcuteComm("srm2_testGetRequestStatus",
	      "$endPoint $gr1_token $gr2_token $gr3_token",
	      "DICTCGe", 0, 
	      "request state", "0",
	      "BLOB");
##$status = ( XtractVal('state\[0\]:') eq '20' ) ? '[OK]' : '[FAILED]';
}

## Crosscheck ...
XcuteComm("dpns-ls -il",
	  "$dpmRoot/$pfxPath | grep \"`date '+%b %d'`\" ", 
	  "DICLSD10", 0,
	  "BLOCK", "",
	  "BLOB");

}

####################################################################################################
sub XtractVal {
    my $string = shift;
##    $flat =~ m/$string\s+(.+?)\s+/;
    my $val = "";
    foreach (@res) {
	if ( /$string\s+(\S+?)\s+/ ) {
	    $val = $1;
	} elsif ( /($string\S*?)\s+/ ) {
	    $val = $1;
	}
    }
    print " XtractVal: >$string< >$val< \n";
    return $val;
}

####################################################################################################
sub XtractValPREV {
    my $string = shift;
    $flat =~ m/$string\s+(.+?)\s+/;
    return $1;
}

####################################################################################################
sub XtractGoodTurl {
    my $TURL = shift;
    my $sTURL;
    	if ( $TURL =~ /rfio/ ) {  
	    $TURL =~ m[(.*?)://.*?/(.*)];
	    $TURL =~ m[(.*?)://(.*)];
	    $sTURL = $2;
	    $sTURL =~ s;//;:/; ;

	    if ( $ENV{NEW_RFIO_SYNTAX} ) {
		$sTURL = $TURL;  ###  For the NEW RFIOD 30/11/05
	    }

	} else {
	    $TURL =~ m[(.*?://.*?)(/.*?:)(/.*)];
	    $sTURL = $1 . $3;

	    $sTURL = $TURL;  ###  For the NEW FTPD 23/05/05

	}
    print " Xtract\n INPUT: $TURL\n OUTPUT: $sTURL\n";
    return $sTURL;
}

####################################################################################################
sub createGftest {
    my $file = shift;

    open SCRIPT, ">$file";
    print SCRIPT <<'END'
dteam001-gfal-S11018-I0000-CElxb2018-WNlxb1715-26136-050524-095725.jpb
dteam001-gfal-S11018-I0000-CElxb2018-WNlxb1715-26136-050524-095725.jpb
dteam001-gfal-S11018-I0000-CElxb2018-WNlxb1715-26136-050524-095725.jpb
dteam001-gfal-S11018-I0000-CElxb2018-WNlxb1715-26136-050524-095725.jpb
dteam001-gfal-S11018-I0000-CElxb2018-WNlxb1715-26136-050524-095725.jpb
dteam001-gfal-S11018-I0000-CElxb2018-WNlxb1715-26136-050524-095725.jpb
dteam001-gfal-S11018-I0000-CElxb2018-WNlxb1715-26136-050524-095725.jpb
dteam001-gfal-S11018-I0000-CElxb2018-WNlxb1715-26136-050524-095725.jpbNN
END
    ;
    close SCRIPT;
    chmod 0444, $file;
}

####################################################################################################
sub createDpmSource {
    my $file = shift;

    open SCRIPT, ">$file";
    if (1) {
    print SCRIPT <<'END'
#setenv LD_LIBRARY_PATH /afs/cern.ch/user/g/grodid/public/lfc-4-gilbert:/opt/lcg/lib:/opt/globus/lib:/opt/edg/lib:/usr/local/lib:/usr/local/lib:/usr/local/lib:/opt/d-cache/dcap/lib:/opt/d-cache/dcap/lib:/opt/d-cache/dcap/lib:/opt/globus/lib:/opt/edg/lib:/opt/globus/lib:/opt/edg/lib
##setenv LCG_GFAL_INFOSYS lxgate22.cern.ch:2135 
setenv DPNS_HOST lxb1706
setenv DPM_HOST lxb1706
setenv LCG_RFIO_TYPE dpm
##setenv LFC_HOST ??
END
    ;
}
    if (0) {
    print SCRIPT <<'END'
##setenv
END
    ;
}
    close SCRIPT;
    chmod 0444, $file;
}

####################################################################################################
sub createGfalTestC {
    my $file = shift;

    open SCRIPT, ">$file";
    print SCRIPT <<'EOC'
/*
 * Copyright (C) 2003 by CERN Jean-Philippe Baud
 * Copyright (C) 2004-2007 by LAL/IN2P3/CNRS Gilbert Grosdidier
 */

#include <fcntl.h>
#include <stdio.h>
#include "gfal_api.h"
#define BLKLEN 65536
#define DEFPOLLINT 10

#include <unistd.h>
//#include <getopt.h>

/* GG/RM 25/06/07 */
#include <stdlib.h>
#include <string.h>

extern char* optarg;
extern int optind, opterr, optopt;


main(int argc, char **argv)
{
	int in_fd;
	int out_fd;
	int i, j;
	char ibuf[BLKLEN];
	char obuf[BLKLEN];
	int rc;
	int count;

	int in_fdc, out_fdc;
	char grogfal[256];
	int ic;

        struct stat statbuf;

	char gstring[128];
	//char* hstring;

	char *fnorig;
	//241107static char **surl = NULL;
	char **surl = NULL;

	// Getting options ...
	int iget;
	//	optind = 1;
	/*char**/ int optiong;

	static char *surlu = {"srm://lxgate22.cern.ch:8443//dpm/cern.ch/home/dteam/dteam001B"};
        char *workdir;

	/* srm_get test block */
#ifdef SRM
//#define SRM 2
#if SRM == 1
	struct srm_filestatus *filestatuses;
#else
	struct srmv2_filestatus *filestatuses;
	int bufsiz = 0;
	int timeout = 100;
        char* r_token;
#endif
	int nbfiles;
	int nbprotocols;
	int nbreplies;
	char *protocols[] = {"rfio","gsidcap",""};
	//static char *protocols[] = {"gsidcap"};
	int r = 0;
	int reqid;
	int fc = 0; // ready file count
	int extra;
#endif


        int igmul;
        int igMul = 1;

        //fflush(NULL);

	while ( (iget = getopt(argc, argv, "+g:D:RW")) != EOF) {
	  switch (iget) {
	  case 'g':
	    {
	      optiong = atoi(optarg);
	      printf ("option %c %d\n", iget, optiong);
	      break;
	    }
	  case 'R':
	  case 'W':
	    {
	      printf ("option %c\n", iget);
	      break;
	    }
	  case 'D':
	    {
              workdir = optarg;
	      printf ("option %c %s\n", iget, workdir);
	      break;
	    }
	  default:
	    {
	      /*
	      dummy = optarg;
	      */
	    }
	  }
	}

	/*
	if (optind < argc) {
	  printf ("non-option ARGV-elements: ");
	  while (optind < argc)
	    printf ("%s ", argv[optind++]);
	  printf ("\n");
	}
	*/
	// End of Options stuff

        fflush(NULL);

	if (argc != 2+optind) {
		fprintf (stderr, "usage: %s unix-filename gfal-filename [%d]\n", argv[0], argc);
		exit (1);
	}

	// Test string read ...
        /*
	scanf("%s", gstring);
	printf (" Some string to read: %s \n", gstring);
        */
	// End of Read test

	for (i = 0; i < BLKLEN; i++)
		obuf[i] = i;

	printf ("reading file %s\n", argv[optind]);
	if ((in_fdc = open (argv[optind], O_RDONLY)) < 0) {
		perror ("unix_open");
		exit (1);
	}
	printf ("unix open successful, in_fdc = %d\n", in_fdc);

	//grogfal = "/tmp/grogfal";
        sprintf(grogfal, "%s/grogfal", workdir);
	printf ("creating file %s\n", grogfal);
        //exit (0);
	//grogfal = "grogfal";
	//printf ("creating file %s\n", grogfal);
	if ((out_fdc = open (grogfal, O_WRONLY|O_CREAT, 0644)) < 0) {
		perror ("grogfal_open_write");
		exit (1);
	}
	printf ("grogfal open_write successful, out_fdc = %d\n", out_fdc);

	while ((i = read(in_fdc, obuf, BLKLEN)) > 0 ) {

	  count++;

	  //for ( ic = 0; ic<15000; ic++ ) {
	  for ( ic = 0; ic<150; ic++ ) {
	    if ((rc = write (out_fdc, obuf, i)) != i) {
	      if (rc < 0)
		perror ("write");
	      else
		fprintf (stderr, "write %d returns %d\n", count, rc);
	      (void) close (out_fdc);
	      exit (1);
	    }
	    //PR printf ("grogfal write %d successful_ic\n", ic);
	  }
	  printf ("grogfal write %d successful_count\n", count);

	}

	if ((rc = close (in_fdc)) < 0) {
		perror ("unix_close");
		exit (1);
	}
	printf ("unix close successful\n");

	if ((rc = close (out_fdc)) < 0) {
		perror ("close");
		exit (1);
	}
	printf ("grogfal close successful\n");

	printf ("reading file %s\n", grogfal);
	if ((in_fd = open (grogfal, O_RDONLY)) < 0) {
		perror ("grogfal_open_read");
		exit (1);
	}
	printf ("grogfal open_read successful, in_fd = %d\n", in_fd);

	surl = (char **) malloc(optiong*sizeof(char*));
	//surl[0] = (char *) malloc(optiong*sizeof(char*));
	fnorig = malloc((size_t) (optiong+1+strlen(argv[1+optind])));
	//fnorig = (char *) malloc(sizeof(char*)*(optiong+1+strlen(argv[1+optind])));
	strcpy(fnorig, argv[1+optind]);

	/* =======================             START of LOOP */
	for (j=0; j<optiong; j++) {

/*  	  surl[j] = malloc((size_t) strlen(fnorig)*sizeof(char)); */
/*  	  strcpy(surl[j], fnorig); */
	  surl[j] = strdup(fnorig);
	  //surl[j] = (char *) strdup(fnorig);
/*  	  printf ("storing filename >%s<\n", fnorig); */
/*  	  printf ("stored filename >%s<\n", surl[j]); */

/*  	printf ("writing file %s\n", argv[1+optind]); */
/*  	if ((out_fd = gfal_open (argv[1+optind], O_WRONLY|O_CREAT, 0644)) < 0) { */
	printf ("writing file %s\n", fnorig);
	if ((out_fd = gfal_open64 (fnorig, O_WRONLY|O_CREAT, 0644)) < 0) {
		perror ("gfal_open64");
		exit (1);
	}
	printf ("gfal_open64 successful, out_fd = %d\n", out_fd);
	count = 0;
        if ( j == 0 )
          igMul = 1;
        else
          igMul *= 3;
/*          igMul *= 13;*/

	while ((i = read(in_fd, obuf, BLKLEN)) > 0 ) {

	  count++;

          for ( igmul = 0; igmul < igMul; igmul++ ) {
	  if ((rc = gfal_write (out_fd, obuf, i)) != i) {
	    if (rc < 0)
	      perror ("gfal_write");
	    else
	      fprintf (stderr, "gfal_write %d returns %d\n", count, rc);
	    (void) gfal_close (out_fd);
	    exit (1);
	  }
          }

	}
	printf ("gfal_write %d successful\n", count);

/*  	if ((rc = close (in_fd)) < 0) { */
/*  		perror ("unix_close"); */
/*  		exit (1); */
/*  	} */
/*  	printf ("unix close successful\n"); */

	if ((rc = gfal_close (out_fd)) < 0) {
		perror ("gfal_close");
		exit (1);
	}
	printf ("gfal_close successful\n");

	strcat(fnorig, "Y");
	close(in_fd);
	in_fd = open (grogfal, O_RDONLY);
	}
	/* =======================             END of LOOP */

#if 0
	printf ("writing file %s\n", surlu);
	if ((out_fd = gfal_open (surlu, O_WRONLY|O_CREAT, 0644)) < 0) {
		perror ("gfal_open");
		exit (1);
	}
	printf ("gfal_open successful, out_fd = %d\n", out_fd);
	count = 0;

	while ((i = read(in_fd, obuf, BLKLEN)) > 0 ) {

	  count++;

	  if ((rc = gfal_write (out_fd, obuf, i)) != i) {
	    if (rc < 0)
	      perror ("gfal_write");
	    else
	      fprintf (stderr, "gfal_write %d returns %d\n", count, rc);
	    (void) gfal_close (out_fd);
	    exit (1);
	  }

	}
	printf ("gfal_write %d successful\n", count);

/*  	if ((rc = close (in_fd)) < 0) { */
/*  		perror ("unix_close"); */
/*  		exit (1); */
/*  	} */
/*  	printf ("unix close successful\n"); */

	if ((rc = gfal_close (out_fd)) < 0) {
		perror ("gfal_close");
		exit (1);
	}
	printf ("gfal_close successful\n");
#endif

	if ((rc = close (in_fd)) < 0) {
		perror ("unix_close");
		exit (1);
	}
	printf ("unix close successful\n");

	count = 0;

	printf ("reading back %s\n", grogfal);

	if ((in_fd = open (grogfal, O_RDONLY, 0)) < 0) {
		perror ("unix_open");
		exit (1);
	}
	printf ("unix open successful, in_fd = %d\n", in_fd);

	if ((out_fd = gfal_open (argv[1+optind], O_RDONLY, 0)) < 0) {
		perror ("gfal_open");
		exit (1);
	}
	printf ("gfal_open successful, out_fd = %d\n", out_fd);

	while ((i = read(in_fd, ibuf, BLKLEN)) > 0 ) {

	  count++;

	  if ((rc = gfal_read (out_fd, obuf, i)) != i) {
	    if (rc < 0)
	      perror ("gfal_read");
	    else
	      fprintf (stderr, "gfal_read %d returns %d\n", count, rc);
	    (void) gfal_close (out_fd);
	    exit (1);
	  }
	  //printf ("gfal read %d successful\n", count);

	  for (j = 0; j < i; j++) {
	    if (ibuf[j] != obuf[j]) {
	      fprintf (stderr, "compare %d failed at offset %d\n", count, j);
	      exit (1);
	    }
	  }

	}
	printf ("compare %d successful\n", count);

	if ((rc = close (in_fd)) < 0) {
		perror ("unix_close");
		exit (1);
	}
	printf ("unix close successful\n");

	if ((rc = gfal_close (out_fd)) < 0) {
		perror ("gfal_close");
		exit (1);
	}
	printf ("gfal_close successful\n");

    // grid or home ?
//	rc = system("nsls -l /castor/cern.ch/home/dteam");
//	rc = system("nsls -l /castor/cern.ch/grid/dteam");

        if (gfal_stat (argv[1+optind], &statbuf) < 0) {
                perror ("gfal_stat");
                exit (1);
        }

        printf ("\ngfal_stat successful\n");
        printf ("mode = %o\n", statbuf.st_mode);
        printf ("nlink = %d\n", statbuf.st_nlink);
        printf ("uid = %d\n", statbuf.st_uid);
        printf ("gid = %d\n", statbuf.st_gid);
        printf ("size = %ld\n", statbuf.st_size);

	rc = unlink(grogfal);

	for (j=0; j<optiong; j++)
	  printf(" surl: %d %s \n", j, surl[j]);

#ifdef SRM
	nbfiles = optiong;
	nbprotocols = sizeof(protocols) / sizeof(char *);

        sleep(10);

//#define SRM 2
#if SRM == 1
//#ifdef SRM
	printf(" Calling srm_get \n");
	if ((nbreplies = srm_get (nbfiles, (const char **) surl, nbprotocols, protocols,
	    &reqid, NULL, &filestatuses, extra)) < 0) {
		perror ("srm_get");
		exit (1);
	}
#else
/*
srmv2_get (int nbfiles, char **surls, char *spacetokendesc, int nbprotocols, char **protocols, char **reqtoken,
       struct srmv2_filestatus **filestatuses, char *errbuf, int errbufsz, int timeout)
*/
	printf(" Calling srmv2_get \n");
	if ((nbreplies = srmv2_get (nbfiles, (const char **) surl, NULL, nbprotocols, protocols,
	    &r_token, &filestatuses, NULL, bufsiz, timeout)) < 0) {
		perror ("srmv2_get");
		exit (1);
	}
#endif

	/* process files as soon as they are "ready" */

	//printf(" srm_get: %d \n", nbreplies);

	while (1) {
	  printf(" srm_get: %d %d %d \n", nbreplies, r, fc);
		for (i = 0; i < nbreplies; i++) {
			if ((filestatuses+i)->status == 1) {	/* file ready */
				/* process it if not yet done */
			  printf(" srm_get: %d %s \n", i, (filestatuses+i)->turl);
			  //printf(" srm_get: %d %d %d \n", i, (filestatuses+i)->surl, (filestatuses+i)->turl);
			  fc++;
			}
			if ((filestatuses+i)->surl)
				free ((filestatuses+i)->surl);
  			if ((filestatuses+i)->turl) 
  				free ((filestatuses+i)->turl); 
			/*(filestatuses+i)->turl = NULL;*/
		}
		free (filestatuses);

		/* if processing complete, break */ /*if (r) break;*/
		/* if processing complete, break */ if (fc==nbreplies) break;

		sleep ((r++ == 0) ? 1 : DEFPOLLINT);
#if SRM == 1
//#ifdef SRM 
	printf(" Calling srm_getstatus \n");
		if ((nbreplies = srm_getstatus (nbfiles, (const char **) surl, reqid, NULL,
		    &filestatuses, extra)) < 0) {
			perror ("srm_getstatus");
			exit (1);
		}
#else
	printf(" Calling srmv2_getstatus \n");
		if ((nbreplies = srmv2_getstatus (nbfiles, (const char **) surl, r_token,
		    &filestatuses, NULL, bufsiz, timeout)) < 0) {
			perror ("srmv2_getstatus");
			exit (1);
		}
#endif
		fc = 0;
	}
#endif

  	if ((rc = gfal_unlink(argv[1+optind])) < 0) { 
  		perror ("gfal_unlink"); 
  		exit (1); 
  	} 
  	printf ("gfal_unlink successful\n"); 

	exit (0);
}

EOC
    ;
    close SCRIPT;
    chmod 0444, $file;
}

####################################################################################################
sub createGfalTestCOLD {
    my $file = shift;

    open SCRIPT, ">$file";
    print SCRIPT <<'EOC'
/*
 * Copyright (C) 2003 by CERN Jean-Philippe Baud
 * Copyright (C) 2004-2006 by LAL/IN2P3/CNRS Gilbert Grosdidier
 */

#include <fcntl.h>
#include <stdio.h>
#include "gfal_api.h"
#define BLKLEN 65536
#define DEFPOLLINT 10

#include <unistd.h>
//#include <getopt.h>

extern char* optarg;
extern int optind, opterr, optopt;


main(int argc, char **argv)
{
	int in_fd;
	int out_fd;
	int i, j;
	char ibuf[BLKLEN];
	char obuf[BLKLEN];
	int rc;
	int count;

	int in_fdc, out_fdc;
	char grogfal[256];
	int ic;

        struct stat statbuf;

	char gstring[128];
	//char* hstring;

	char *fnorig;
	static char **surl = NULL;

	// Getting options ...
	int iget;
	//	optind = 1;
	/*char**/ int optiong;

	static char *surlu = {"srm://lxgate22.cern.ch:8443//dpm/cern.ch/home/dteam/dteam001B"};
        char *workdir;

	/* srm_get test block */
#if 1
	struct srm_filestatus *filestatuses;
	int nbfiles;
	int nbprotocols;
	int nbreplies;
	static char *protocols[] = {"rfio","gsidcap"};
	//static char *protocols[] = {"gsidcap"};
	int r = 0;
	int reqid;
	int fc = 0; // ready file count
	int extra;
#endif

        int igmul;
        int igMul = 1;

        //fflush(NULL);

	while ( (iget = getopt(argc, argv, "+g:D:RW")) != EOF) {
	  switch (iget) {
	  case 'g':
	    {
	      optiong = atoi(optarg);
	      printf ("option %c %d\n", iget, optiong);
	      break;
	    }
	  case 'R':
	  case 'W':
	    {
	      printf ("option %c\n", iget);
	      break;
	    }
	  case 'D':
	    {
              workdir = optarg;
	      printf ("option %c %s\n", iget, workdir);
	      break;
	    }
	  default:
	    {
	      /*
	      dummy = optarg;
	      */
	    }
	  }
	}

	/*
	if (optind < argc) {
	  printf ("non-option ARGV-elements: ");
	  while (optind < argc)
	    printf ("%s ", argv[optind++]);
	  printf ("\n");
	}
	*/
	// End of Options stuff

        fflush(NULL);

	if (argc != 2+optind) {
		fprintf (stderr, "usage: %s unix-filename gfal-filename [%d]\n", argv[0], argc);
		exit (1);
	}

	// Test string read ...
        /*
	scanf("%s", gstring);
	printf (" Some string to read: %s \n", gstring);
        */
	// End of Read test

	for (i = 0; i < BLKLEN; i++)
		obuf[i] = i;

	printf ("reading file %s\n", argv[optind]);
	if ((in_fdc = open (argv[optind], O_RDONLY)) < 0) {
		perror ("unix_open");
		exit (1);
	}
	printf ("unix open successful, in_fdc = %d\n", in_fdc);

	//grogfal = "/tmp/grogfal";
        sprintf(grogfal, "%s/grogfal", workdir);
	printf ("creating file %s\n", grogfal);
        //exit (0);
	//grogfal = "grogfal";
	//printf ("creating file %s\n", grogfal);
	if ((out_fdc = open (grogfal, O_WRONLY|O_CREAT, 0644)) < 0) {
		perror ("grogfal_open_write");
		exit (1);
	}
	printf ("grogfal open_write successful, out_fdc = %d\n", out_fdc);

	while ((i = read(in_fdc, obuf, BLKLEN)) > 0 ) {

	  count++;

	  //for ( ic = 0; ic<15000; ic++ ) {
	  for ( ic = 0; ic<150; ic++ ) {
	    if ((rc = write (out_fdc, obuf, i)) != i) {
	      if (rc < 0)
		perror ("write");
	      else
		fprintf (stderr, "write %d returns %d\n", count, rc);
	      (void) close (out_fdc);
	      exit (1);
	    }
	    //PR printf ("grogfal write %d successful_ic\n", ic);
	  }
	  printf ("grogfal write %d successful_count\n", count);

	}

	if ((rc = close (in_fdc)) < 0) {
		perror ("unix_close");
		exit (1);
	}
	printf ("unix close successful\n");

	if ((rc = close (out_fdc)) < 0) {
		perror ("close");
		exit (1);
	}
	printf ("grogfal close successful\n");

	printf ("reading file %s\n", grogfal);
	if ((in_fd = open (grogfal, O_RDONLY)) < 0) {
		perror ("grogfal_open_read");
		exit (1);
	}
	printf ("grogfal open_read successful, in_fd = %d\n", in_fd);

	surl = malloc(optiong*sizeof(char*));
	fnorig = malloc((size_t) (optiong+1+strlen(argv[1+optind])));
	strcpy(fnorig, argv[1+optind]);

	/* =======================             START of LOOP */
	for (j=0; j<optiong; j++) {

/*  	  surl[j] = malloc((size_t) strlen(fnorig)*sizeof(char)); */
/*  	  strcpy(surl[j], fnorig); */
	  surl[j] = strdup(fnorig);
/*  	  printf ("storing filename >%s<\n", fnorig); */
/*  	  printf ("stored filename >%s<\n", surl[j]); */

/*  	printf ("writing file %s\n", argv[1+optind]); */
/*  	if ((out_fd = gfal_open (argv[1+optind], O_WRONLY|O_CREAT, 0644)) < 0) { */
	printf ("writing file %s\n", fnorig);
	if ((out_fd = gfal_open (fnorig, O_WRONLY|O_CREAT, 0644)) < 0) {
		perror ("gfal_open");
		exit (1);
	}
	printf ("gfal_open successful, out_fd = %d\n", out_fd);
	count = 0;
        if ( j == 0 )
          igMul = 1;
        else
          igMul *= 3;

	while ((i = read(in_fd, obuf, BLKLEN)) > 0 ) {

	  count++;

          for ( igmul = 0; igmul < igMul; igmul++ ) {
	  if ((rc = gfal_write (out_fd, obuf, i)) != i) {
	    if (rc < 0)
	      perror ("gfal_write");
	    else
	      fprintf (stderr, "gfal_write %d returns %d\n", count, rc);
	    (void) gfal_close (out_fd);
	    exit (1);
	  }
          }

	}
	printf ("gfal_write %d successful\n", count);

/*  	if ((rc = close (in_fd)) < 0) { */
/*  		perror ("unix_close"); */
/*  		exit (1); */
/*  	} */
/*  	printf ("unix close successful\n"); */

	if ((rc = gfal_close (out_fd)) < 0) {
		perror ("gfal_close");
		exit (1);
	}
	printf ("gfal_close successful\n");

	strcat(fnorig, "Y");
	close(in_fd);
	in_fd = open (grogfal, O_RDONLY);
	}
	/* =======================             END of LOOP */

#if 0
	printf ("writing file %s\n", surlu);
	if ((out_fd = gfal_open (surlu, O_WRONLY|O_CREAT, 0644)) < 0) {
		perror ("gfal_open");
		exit (1);
	}
	printf ("gfal_open successful, out_fd = %d\n", out_fd);
	count = 0;

	while ((i = read(in_fd, obuf, BLKLEN)) > 0 ) {

	  count++;

	  if ((rc = gfal_write (out_fd, obuf, i)) != i) {
	    if (rc < 0)
	      perror ("gfal_write");
	    else
	      fprintf (stderr, "gfal_write %d returns %d\n", count, rc);
	    (void) gfal_close (out_fd);
	    exit (1);
	  }

	}
	printf ("gfal_write %d successful\n", count);

/*  	if ((rc = close (in_fd)) < 0) { */
/*  		perror ("unix_close"); */
/*  		exit (1); */
/*  	} */
/*  	printf ("unix close successful\n"); */

	if ((rc = gfal_close (out_fd)) < 0) {
		perror ("gfal_close");
		exit (1);
	}
	printf ("gfal_close successful\n");
#endif

	if ((rc = close (in_fd)) < 0) {
		perror ("unix_close");
		exit (1);
	}
	printf ("unix close successful\n");

	count = 0;

	printf ("reading back %s\n", grogfal);

	if ((in_fd = open (grogfal, O_RDONLY, 0)) < 0) {
		perror ("unix_open");
		exit (1);
	}
	printf ("unix open successful, in_fd = %d\n", in_fd);

	if ((out_fd = gfal_open (argv[1+optind], O_RDONLY, 0)) < 0) {
		perror ("gfal_open");
		exit (1);
	}
	printf ("gfal_open successful, out_fd = %d\n", out_fd);

	while ((i = read(in_fd, ibuf, BLKLEN)) > 0 ) {

	  count++;

	  if ((rc = gfal_read (out_fd, obuf, i)) != i) {
	    if (rc < 0)
	      perror ("gfal_read");
	    else
	      fprintf (stderr, "gfal_read %d returns %d\n", count, rc);
	    (void) gfal_close (out_fd);
	    exit (1);
	  }
	  //printf ("gfal read %d successful\n", count);

	  for (j = 0; j < i; j++) {
	    if (ibuf[j] != obuf[j]) {
	      fprintf (stderr, "compare %d failed at offset %d\n", count, j);
	      exit (1);
	    }
	  }

	}
	printf ("compare %d successful\n", count);

	if ((rc = close (in_fd)) < 0) {
		perror ("unix_close");
		exit (1);
	}
	printf ("unix close successful\n");

	if ((rc = gfal_close (out_fd)) < 0) {
		perror ("gfal_close");
		exit (1);
	}
	printf ("gfal_close successful\n");

    // grid or home ?
//	rc = system("nsls -l /castor/cern.ch/home/dteam");
//	rc = system("nsls -l /castor/cern.ch/grid/dteam");

        if (gfal_stat (argv[1+optind], &statbuf) < 0) {
                perror ("gfal_stat");
                exit (1);
        }

        printf ("\ngfal_stat successful\n");
        printf ("mode = %o\n", statbuf.st_mode);
        printf ("nlink = %d\n", statbuf.st_nlink);
        printf ("uid = %d\n", statbuf.st_uid);
        printf ("gid = %d\n", statbuf.st_gid);
        printf ("size = %ld\n", statbuf.st_size);

	rc = unlink(grogfal);

	for (j=0; j<optiong; j++)
	  printf(" surl: %d %s \n", j, surl[j]);

#if 1
	nbfiles = optiong;
	nbprotocols = sizeof(protocols) / sizeof(char *);

        sleep(10);

	if ((nbreplies = srm_get (nbfiles, surl, nbprotocols, protocols,
	    &reqid, NULL, &filestatuses, extra)) < 0) {
		perror ("srm_get");
		exit (1);
	}

	/* process files as soon as they are "ready" */

	//printf(" srm_get: %d \n", nbreplies);

	while (1) {
	  printf(" srm_get: %d %d %d \n", nbreplies, r, fc);
		for (i = 0; i < nbreplies; i++) {
			if ((filestatuses+i)->status == 1) {	/* file ready */
				/* process it if not yet done */
			  printf(" srm_get: %d %s \n", i, (filestatuses+i)->turl);
			  //printf(" srm_get: %d %d %d \n", i, (filestatuses+i)->surl, (filestatuses+i)->turl);
			  fc++;
			}
			if ((filestatuses+i)->surl)
				free ((filestatuses+i)->surl);
  			if ((filestatuses+i)->turl) 
  				free ((filestatuses+i)->turl); 
			/*(filestatuses+i)->turl = NULL;*/
		}
		free (filestatuses);

		/* if processing complete, break */ /*if (r) break;*/
		/* if processing complete, break */ if (fc==nbreplies) break;

		sleep ((r++ == 0) ? 1 : DEFPOLLINT);
		if ((nbreplies = srm_getstatus (nbfiles, surl, reqid, NULL,
		    &filestatuses, extra)) < 0) {
			perror ("srm_getstatus");
			exit (1);
		}
		fc = 0;
	}
#endif

  	if ((rc = gfal_unlink(argv[1+optind])) < 0) { 
  		perror ("gfal_unlink"); 
  		exit (1); 
  	} 
  	printf ("gfal_unlink successful\n"); 

	exit (0);
}

EOC
    ;
    close SCRIPT;
    chmod 0444, $file;
}

####################################################################################################
sub CreateProxy {
     unless ( $ENV{GSI_PASSWORD} ) {
	 print STDERR "ERROR in GSI_PASSWORD checking: please define the GSI_PASSWORD variable (your GSI certificate pwd) ...\n";
	 exit 1;
     }

     ## Special to voms-proxy-init testing ...
     my $specialGlite = 0;
     my $savePathLIB = $ENV{LD_LIBRARY_PATH};
     my $savePathBIN = $ENV{PATH};
     if ( $specialGlite ) {
	 $ENV{LD_LIBRARY_PATH} = "/opt/lcg/RpmDir/opt/glite/lib:$savePathLIB";
	 $ENV{PATH} = "/opt/lcg/RpmDir/opt/glite/bin:$savePathBIN";
     }
     ## Special to voms-proxy-init testing ...

     system("which voms-proxy-init");
     system("which voms-proxy-info");

     ## Creating the vomses file ...
     open VMS, ">vomses";
     printf VMS <<'EVMS';
"dteam" "lcg-voms.cern.ch" "15004" "/C=CH/O=CERN/OU=GRID/CN=host/lcg-voms.cern.ch" "dteam"
"lhcb" "lcg-voms.cern.ch" "15003" "/C=CH/O=CERN/OU=GRID/CN=host/lcg-voms.cern.ch" "lhcb"
"ops" "lcg-voms.cern.ch" "15009" "/C=CH/O=CERN/OU=GRID/CN=host/lcg-voms.cern.ch" "ops"
EVMS
     close VMS;

## Just in case ...
## "dteam" "voms.cern.ch" "15004" "/DC=ch/DC=cern/OU=computers/CN=voms.cern.ch" "dteam"
## "lhcb" "voms.cern.ch" "15003" "/DC=ch/DC=cern/OU=computers/CN=voms.cern.ch" "lhcb"


     ## Building the command string ...
     my $savePath;
     my $rcp;
     my $vomsCom;
     my $certIN = "  ";
     my $vomsVO = 'dteam';

     ## Some specificities ...
     if ( $certA eq 'lhcb' ) {
	 if ( $proxyT ne 'voms' ) {
	     print STDERR " Proxy Type error: $proxyT for $certA \n";
	     exit 1;
	 }
	 $certA  = 'ppdg';
	 $vomsVO = 'lhcb';
     } elsif ( $certA eq 'ops' ) {
	 if ( $proxyT ne 'voms' ) {
	     print STDERR " Proxy Type error: $proxyT for $certA \n";
	     exit 1;
	 }
	 $certA  = 'cern';
	 $vomsVO = 'ops';
     }

     if ( $ENV{USER} eq 'grodid' && $certA ne 'NADA' ) {
	 $certIN = "$ENV{GSI_AREA}/${certA}-2008";
	 $certIN = " -cert ${certIN}/usercert.pem -key ${certIN}/userkey.pem ";
     }

##OLD     my $proxyF = "${tempDir}/x509up_u1110_${proxyT}_${sfile}";
     my $proxyF = "${tempDir}/x509up_u1110_${proxyT}_${certA}_${vomsVO}_${sfile}";
     if ( $proxyT eq "globus" ) {
	 $vomsCom = "voms-proxy-init -valid 300:00 -out $proxyF -pwstdin";
	 $proxyI = 'G';
	 ##@res = `echo $ENV{GSI_PASSWORD} | $vomsCom 2>&1`;
	 ##$rcp = XtractVal("Creating proxy");
     } elsif ( $proxyT eq "voms" ) {
	 ##$vomsCom = "voms-proxy-init -valid 300:00 -voms dteam -out $proxyF -confile vomses -pwstdin";
	 $vomsCom = "voms-proxy-init -valid 300:00 -voms $vomsVO -out $proxyF -pwstdin";
	 $proxyI = 'V';
     } elsif ( $proxyT eq "vomsR" ) {
	 $vomsCom = "voms-proxy-init -valid 300:00 -voms dteam:/dteam/Role=operator -vomslife 4:00 -out $proxyF -confile vomses -pwstdin";
	 $proxyI = 'R';
     } elsif ( $proxyT eq "extern" ) {
	 print STDOUT " Proxy Type extern: $ENV{X509_USER_PROXY} \n";
	 $proxyF = $ENV{X509_USER_PROXY};
	 $proxyI = 'T';
     } elsif ( $proxyT eq "expired" ) {
	 $savePath = "$ENV{LD_LIBRARY_PATH}";
	 $ENV{LD_LIBRARY_PATH} = "/opt/glite/lib:$savePath";
	 ## This one will be valid for 1 minute only ...
	 $vomsCom = "/opt/glite/bin/voms-proxy-init -valid 300:00 -voms dteam:/dteam/Role=operator -vomslife 00:01 -noregen -confile /afs/cern.ch/project/gd/grodid/SLC3-CVS-dpm-142gk/LCG-DM/test/dpm/vomsesdir -out $proxyF -pwstdin";
	 $proxyI = 'X';
     } else {
	 print STDERR " Proxy Type error: $proxyT \n";
	 exit 1;
     }

     ## Creating the proxy ...
     $vomsCom .= "$certIN";
     if ( $proxyT ne "extern" ) {
	 print STDOUT " VomsCMD: $vomsCom \n";
	 @res = `echo $ENV{GSI_PASSWORD} | $vomsCom 2>&1`;
	 &RemDots();
	 $rcp = XtractVal("Creating proxy");
	 if ( $rcp ne "Done" ) {
	     print STDERR " Proxy does not seem to be properly created: $rcp \n";
	     foreach ( @res ) {
		 print STDERR " FAILURE: $_";
	     }
	     exit 1;
	 }
# 	 else {
# 	     foreach ( @res ) {
# 		 print;
# 	     }
# 	 }
	 $ENV{X509_USER_PROXY} = "$proxyF";
     }

     ## Checking the proxy is valid ...
     if ( $proxyT eq "expired" ) { 
	 $ENV{LD_LIBRARY_PATH} = "$savePath";
	 sleep 380; 
     }
     @res = `voms-proxy-info -all 2>&1`;
     &RemCols();
     $rcp = XtractVal("path:");
     if ( $rcp ne "$proxyF" ) {
	 print STDERR " Proxy does not seem to have the right path: $rcp \n";
	 foreach ( @res ) {
	     print STDERR " FAILURE: $_";
	 }
	 exit 1;
     }
     if ( $proxyT eq "expired" ) {
	 $rcp = XtractVal("timeleft:");
	 if ( $rcp ne "0:00:00" ) {
	     print STDERR " Proxy does not seem to be expired, since timeleft: $rcp \n";
	     foreach ( @res ) {
		 print STDERR " FAILURE: $_";
	     }
	     exit 1;
	 }
     }

     ## Special to voms-proxy-init testing ...
     if ( $specialGlite ) {
	 $ENV{LD_LIBRARY_PATH} = "$savePathLIB";
	 $ENV{PATH} = "$savePathBIN";
     }
     ## Special to voms-proxy-init testing ...

####   exit 0;
 }

####################################################################################################
sub createGilbOld {
    my $file = shift;
    my $orig = shift;
    system("cat $orig $orig > $file");

    chmod 0444, $file;
}

####################################################################################################
sub rfioSuite {

my $direct = shift;
my $fmach  = shift;
if ( $dServer0 && $direct eq 'NODPM' ) { $fmach = $dServer0; }

    my $suite = 'rfioSuite';
    ##$xCount++;
    chomp($dateST = `date '+%y%m%d-%H%M%S'`);
    print "\n++++ $$ $dateST\n";
    print " STEP: $xCount OPERATION: $suite CMD: $suite $direct $fmach\n";

    my $tStart = time();

my $rinitS1 = "DPMsource.flxb1706S1";
####createDpmSource($rinit2);
##my $finit2 = "file:$ENV{PWD}/$rinit2";
####my $finit2 = "file:$tempDir/$rinit2";
my $lfnS1 = "rfcp_Tfile.${sfile}S1";
my $frrootS1 = "$fmach:/tmp/$pfxPath";
if ( $direct eq "DPM" ) {
    $frrootS1 = "$dpmRoot/$pfxPath";
}
my $fremotS1 = "$frrootS1/$lfnS1";

my $rinitS2 = "DPMsource.flxb1706S2";
my $lfnS2 = "rfcp_Tfile.${sfile}S2";
my $frrootS2 = "$fmach:/tmp/$pfxPath/subfDirS1";
if ( $direct eq "DPM" ) {
    $frrootS2 = "$dpmRoot/$pfxPath/subfDirS1";
}
my $fremotS2 = "$frrootS2/$lfnS2";

if (0) {
my $lfnS2 = "rfcp_Tfile.${sfile}S2";
my $frrootS2 = "$fmach:/tmp/$pfxPath/subfDirS1";
if ( $direct eq "DPM" ) {
    $frrootS2 = "$dpmRoot/$pfxPath/subfDirS1";
}
}
my $fremotS3 = "$frrootS2/$lfnS1";

system("cat $rinit2 $rinit2 > $rinitS1");
system("cat $rinit2 $rinit2 $rinit2 > $rinitS2");
my $flinitS1 = "$tempDir/$rinitS1";
my $flinitS2 = "$tempDir/$rinitS2";

$statusLocal = "[OK]";

if ( "$direct" ne "DPM" ) {
XcuteComm("rfmkdir",
	  "-m 755 -p $frrootS1", 
	  "RFMKS0", 0,
	  "EMPTY", "",
	  "BLOB");
}

## Direct rfcp ...
XcuteComm("rfcp",
	  "$flinitS1 $fremotS1", 
	  "RFCPS1", 0,
	  "seconds through local", "",
	  "BLOB");

XcuteComm("rfstat",
	  "$fremotS1", 
	  "RFSTS1", 0,
	  "Last stat. mod. :", "",
	  "BLOB");

my $fremodS1 = "$frrootS1/subfDirS1";

XcuteComm("rfmkdir",
	  "-m 777 -p $fremodS1", 
	  "RFMKS1", 0,
	  "EMPTY", "",
	  "BLOB");

## rfcp -v2 ... in the new dir
XcuteComm("rfcp",
	  "-v2 $flinitS2 $fremotS2", 
	  "RFCPS2", 0,
	  "seconds through local", "",
	  "BLOB");

XcuteComm("rfrename",
	  "$fremotS1 $fremotS3", 
	  "RFMVS1", 0,
	  "EMPTY", "",
	  "BLOB");

XcuteComm("rfdir",
	  "$fremodS1", 
	  "RFLSS1", 0,
	  "$lfnS1", "",
	  "BLOB");

##exit 0;

XcuteComm("rfrm",
	  "$fremodS1", 
	  "RFRMS1", 0,
	  "$fremodS1", "directory",
	  "BLOB");

XcuteComm("rfcp",
	  "-v2 $fremotS2 $tempDir/fcrapS2$direct", 
	  "RFFRS2", 0,
	  "seconds through eth", "",
	  "BLOB");

XcuteComm("rfcp",
	  "$fremotS3 $tempDir/fcrapS1$direct", 
	  "RFFRS3", 0,
	  "seconds through eth", "",
	  "BLOB");
if (0) {
XcuteComm("rfrm",
	  "$fremotS2", 
	  "RFRMS2", 0,
	  "EMPTY", "",
	  "BLOB");

XcuteComm("rfrm",
	  "$fremotS3", 
	  "RFRMS3", 0,
	  "EMPTY", "",
	  "BLOB");
}

XcuteComm("rfrm",
	  "-rf $fremodS1", 
	  "RFRFS1", 0,
	  "EMPTY", "",
	  "BLOB");

XcuteComm("rfdir",
	  "$fremodS1", 
	  "RFLSS2", 0,
	  "No such file or directory", "",
	  "BLOB");

XcuteComm("diff",
	  "-s $flinitS1 $tempDir/fcrapS1$direct", 
	  "RFCMS1", 0,
	  "$tempDir/fcrapS1$direct are", "identical",
	  "BLOB");

XcuteComm("diff",
	  "-s $flinitS2 $tempDir/fcrapS2$direct", 
	  "RFCMS2", 0,
	  "$tempDir/fcrapS2$direct are", "identical",
	  "BLOB");

if (0) {
XcuteComm("rfcp",
	  "$dpmRoot/$pfxPath/$lfn2 $tempDir/fcrap2", 
	  "FCPR", 0,
	  "seconds through eth", "",
	  "BLOB");
}

	my $tEnd = time();
	my $tElapse = $tEnd - $tStart;
	print "\n Operation: rfioSuite with $direct = $statusLocal Duration: $tElapse sec. \n";
	print "<_________________________________________________________________________>\n\n";
        print " Result:  Status: $statusLocal\n";
        $xCount++;
	if ( $statusLocal eq "[OK]" ) { $globOK++; }
	if ( $statusLocal eq "[FAILED]" ) { $globFD++; }
        undef $statusLocal;

}

####################################################################################################
sub gsiftpSuite {

my $direct = shift;
my $fmach  = shift;
if ( $dServer0 ) { $fmach = $dServer0; }

my $gVers = $gsiftpV{$fmach};

    my $suite = 'gsiftpSuite';
    ##$xCount++;
    chomp($dateST = `date '+%y%m%d-%H%M%S'`);
    print "\n++++ $$ $dateST\n";
    print " STEP: $xCount OPERATION: $suite CMD: $suite $direct $fmach\n";

    my $tStart = time();

my $rinitS1 = "DPMsource.glxb1706S1";
####createDpmSource($rinit2);
##my $finit2 = "file:$ENV{PWD}/$rinit2";
####my $finit2 = "file:$tempDir/$rinit2";
my $lfnS1 = "gsiftp_Tfile.${sfile}S1";
my $frrootS1 = "gsiftp://$fmach/$fmach:/tmp/$pfxPath";
if ( $direct eq "DPM" ) {
    $frrootS1 = "gsiftp://${fmach}$dpmRoot/$pfxPath";
}
my $fremotS1 = "$frrootS1/$lfnS1";

my $rinitS2 = "DPMsource.lxb1706S2";
my $lfnS2 = "gsiftp_Tfile.${sfile}S2";
my $frrootS2 = "gsiftp://$fmach/$fmach:/tmp/$pfxPath/subgDirS1";
if ( $direct eq "DPM" ) {
    $frrootS2 = "gsiftp://${fmach}$dpmRoot/$pfxPath/subgDirS1";
}
my $fremotS2 = "$frrootS2/$lfnS2";

if (0) {
my $lfnS2 = "gsiftp_Tfile.${sfile}S2";
my $frrootS2 = "gsiftp://$fmach/$fmach:/tmp/$pfxPath/subgDirS1";
if ( $direct eq "DPM" ) {
    $frrootS2 = "gsiftp://${fmach}$dpmRoot/$pfxPath/subgDirS1";
}
}
my $fremotS3 = "$frrootS2/$lfnS1";

system("cat $rinit2 $rinit2 $rinit2 $rinit2 > $rinitS1");
system("cat $rinit2 $rinit2 $rinit2 $rinit2 $rinit2 > $rinitS2");
my $flinitS1 = "$tempDir/$rinitS1";
my $flinitS2 = "$tempDir/$rinitS2";

$statusLocal = "[OK]";

## Direct rfcp ...
XcuteComm("globus-url-copy",
	  "-dbg file:$flinitS1 $fremotS1", 
	  "GTCPS1", 0,
	  "$gsiTrfMs{$gVers}", "",
	  "BLOB");
##	  "226 Transfer complete.", "",

XcuteComm("edg-gridftp-exists",
	  "$fremotS1", 
	  "GTSTS1", 0,
	  "EMPTY", "",
	  "BLOB");

my $fremodS1 = "$frrootS1/subgDirS1";

XcuteComm("edg-gridftp-mkdir",
	  "--parents $fremodS1", 
	  "GTMKS1", 0,
	  "EMPTY", "",
	  "BLOB");

if (0) {
## rfcp -v2 ... in the new dir
XcuteComm("rfcp",
	  "-v2 $flinitS2 $fremotS2", 
	  "GTCPS2", 0,
	  "seconds through local", "",
	  "BLOB");
}

XcuteComm("edg-gridftp-rename",
	  "$fremotS1 $fremotS3", 
	  "GTMVS1", 0,
	  "EMPTY", "",
	  "BLOB");

XcuteComm("edg-gridftp-ls",
	  "--verbose $fremodS1", 
	  "GTLSS1", 0,
	  "$lfnS1", "",
	  "BLOB");

## For JPB comfort ...
if (1) {
XcuteComm("edg-gridftp-rmdir",
	  "$fremodS1", 
	  "GTRMS1", 0,
	  "$gsiRmdMs{$gVers}", "",
	  "BLOB");
}
##	  "subgDirS1:", "Directory",

if (0) {
XcuteComm("rfcp",
	  "-v2 $fremotS2 $tempDir/fcrapS2$direct", 
	  "GTFRS2", 0,
	  "seconds through eth", "",
	  "BLOB");
}

XcuteComm("globus-url-copy",
	  "-dbg $fremotS3 file:$tempDir/gcrapS1$direct", 
	  "GTFRS3", 0,
	  "$gsiTrfMs{$gVers}", "",
	  "BLOB");
##	  "226 Transfer complete.", "",

if (0) {
XcuteComm("edg-gridftp-rm",
	  "$fremotS2", 
	  "GTRMS2", 0,
	  "EMPTY", "",
	  "BLOB");
}

XcuteComm("edg-gridftp-rm",
	  "$fremotS3", 
	  "GTRMS3", 0,
	  "EMPTY", "",
	  "BLOB");

## For JPB comfort as well ...
if (1) {
XcuteComm("edg-gridftp-rmdir",
	  "$fremodS1", 
	  "GTRFS1", 0,
	  "EMPTY", "",
	  "BLOB");
}

XcuteComm("edg-gridftp-ls",
	  "--verbose $fremodS1", 
	  "GTLSS2", 0,
	  "$gsiLsMs{$gVers}", "",
	  "BLOB");
#	  "No such file or directory.", "",

XcuteComm("diff",
	  "-s $flinitS1 $tempDir/gcrapS1$direct", 
	  "GTCMS1", 0,
	  "$tempDir/gcrapS1$direct are", "identical",
	  "BLOB");

if (0) {
XcuteComm("diff",
	  "-s $flinitS2 $tempDir/fcrapS2$direct", 
	  "GTCMS2", 0,
	  "$tempDir/fcrapS2$direct are", "identical",
	  "BLOB");
}

if (0) {
XcuteComm("rfcp",
	  "$dpmRoot/$pfxPath/$lfn2 $tempDir/fcrap2", 
	  "FCPR", 0,
	  "seconds through eth", "",
	  "BLOB");
}

	my $tEnd = time();
	my $tElapse = $tEnd - $tStart;
	print "\n Operation: gsiftpSuite with $direct = $statusLocal Duration: $tElapse sec. \n";
	print "<_________________________________________________________________________>\n\n";
        print " Result:  Status: $status\n";
        $xCount++;
	if ( $statusLocal eq "[OK]" ) { $globOK++; }
	if ( $statusLocal eq "[FAILED]" ) { $globFD++; }
        undef $statusLocal;

}
