#!/usr/local/bin/perl -w
#

$homedir=`cd; pwd`; chomp($homedir);

#$host="aldaqpc018";


if ($#ARGV >= 3){
    $spdmoodsite = "$ARGV[0]";
    $hostname = "$ARGV[1]";
    $runNr = "$ARGV[2]";
    $remoteFileName = "$ARGV[3]";
    if ($#ARGV >= 4){
	$localFileName = "$ARGV[4]";
    }
}
else {
    die print "Usage: perl screenShot.pl spdmoodsite hostname webFileName [localFileName]\n";
    # webFileName = "000" if not saving to web
}

#$spdmoodsite = `echo $SPDMOOD_SITE`; chomp($spdmoodsite);

#$hostname = `echo $HOSTNAME`; chomp($hostname);
if ($hostname ne "pcpix110") {
    if ($remoteFileName ne "000") {
	$remoteFileName="000";
	print "WARNING: Remote uploading available only in DSF.\n";
    }
}

$tmpName=$remoteFileName;
if ($tmpName eq "000") {
    @spl = split("/",$localFileName);
    $last = scalar(@spl)-1;
    $tmpName = $spl[$last];
}
$fulltmpName = "$spdmoodsite/bin/tmp/$tmpName";



# let user make screenshot, and save locally
$command = "import $fulltmpName";
#print "$command\n";
system($command);



### upload to remote web ###
if ($remoteFileName ne "000") {
    # make tmp dir at aldaqpc018
    $command="ssh pixel\@aldaqpc018 'mkdir /home/pixel/tmpRun$runNr 2>/dev/null; exit'";
#    print "$command\n";
    system($command);

    # copy to aldaqpc018
    $command="scp $fulltmpName pixel\@aldaqpc018:/home/pixel/tmpRun$runNr/. 1>/dev/null";
#    print "$command\n";
    system($command);

    # run script on aldaqpc018 (to upload the file)
    $command="ssh pixel\@aldaqpc018 'UPLOAD_IMAGES.pl $runNr /home/pixel/tmpRun$runNr; exit'";
#    print "$command\n";
    system($command);

    # remove file and dir from aldaqpc018
    $command="ssh pixel\@aldaqpc018 'rm -f /home/pixel/tmpRun$runNr/$tmpName; rmdir /home/pixel/tmpRun$runNr; exit'";
#    print "$command\n";
    system($command)
}


### save a local copy ###
if ($#ARGV >= 2){
    $command="cp $fulltmpName $localFileName";
#    print "$command\n";
    system($command)
}


### remove tmp local copy ###
$command="rm -f $fulltmpName";
#print "$command\n";
system($command)

