#
# BackupRawData.pl
#
# Backs up raw data (strun root and stlog txt files) from a 
# given sctdaq run into a backup directory under $backup (defined in
# LocalVariables.pl).
#
# Syntax: BackupRawData.pl <Run>
# (You probably need to say perl BackupRawData.pl... on Windows)
#
# If installing this script afresh on a new system, you also need the perl
# libraries SctDAQWebLib.pl and LocalVariables.pl; You should (at least) look
# at LocalVariables.pl to check it is OK for your local system
#
# It is expected this script will run on Windows, but it should work on Unix
# with changes only being needed in LocalVariables.pl (your mileage may 
# differ: feedback welcome) plus perhaps your #!path-to-perl on the first 
# line of this script - if there is no path-to-perl, run the script via
#
#   perl BackupRawData.pl <arguments>
#
# Send feedback to Dave.Charlton@cern.ch
#
# Version 0.1 DGC 2002/05/17  First version, heavy re-use of Peter's 
#                             BackupRawData algorithms

require "SctDAQWebLib.pl" || die "Cannot load SctDAQWebLib.pl" ;
&InitialiseVariables ;

if ( $#ARGV!=0 ) {
    print "syntax: $0 <run>\n" ;
    die "bad arguments" ;
}
$Run=$ARGV[0] ;

$InputDir="$rawdatadir" ;
die "Raw data directory $InputDir does not exist" if ! -d $InputDir ;

$BackupDir="$backup/$ComputerName" ;
if (!-d $BackupDir) {
    print "Making target directory $BackupDir\n" ;
    mkdir $BackupDir,0777 ;
}
$RunDir=$BackupDir . "/" . substr("000000" . $Run,-6) ;
print "$RunDir\n" ;
if (!-d "$RunDir") {
    print "Making target directory $RunDir\n" ;
    mkdir "$RunDir",0777 ;
}
else {
    print "Re-using existing directory $RunDir\n" ;
}

opendir(DATAD,$InputDir) ;
@rootfiles=grep{/^strun$Run\_/} readdir(DATAD) ;
closedir(DATAD) ;

$root_files_copied=0 ;
foreach $f (@rootfiles) {
    if (!-e "$RunDir/$f") {
	&CopyFile("$InputDir/$f","$RunDir/$f") ;
	$root_files_copied++ ;
    }
}

print $#rootfiles+1 . " ROOT files found, of which $root_files_copied needed backing up\n" ;

if ($root_files_copied>0) {
    if (-e "$InputDir/stlog$Run\.txt") {
	&CopyFile("$InputDir/stlog$Run\.txt","$RunDir/stlog$Run\.txt") ;
	print "...so also copied stlog$Run\.txt file\n" ;
    }
    else {
	print "Failed to find $InputDir/stlog$Run\.txt file to back up\n" ;
    }	
}

print "\n$0 execution complete\n" ;
exit 0 ;


