#!/usr/local/bin/perl
#
#
#==============================================================
#
#  Abs:  This script moves elog entries created by java HLApps
#        from the app's staging area, $PHYSICS_DATA/logbook/data,
#        to physics-elog host, dir /var/www/lclselog/data.
#        Based upon today's date, it creates the appropriate directory
#        name underneath  physics-elog:/var/www/lclselog/data.
#        It sleeps for n seconds, wakes up, and looks for xml files in 
#        the staging area. If files are found, it validity checks the
#        xml format and the file links contained within. After validation,
#        the file (set) is first copied to the physics-elog:/var/www/lcls/data/*
#        area. Then the file (set) is copied to the  backup dir on physics-elog
#        host. Then the file (set) is removed from $PHYSICS_DATA/logbook/data area.
#        For every processing interval, it ceases processing if the number of files
#        moved exceeds a specified number prior to sleeping again.  Conditions are
#        logged to a log file in the $PHYSICS_DATA/slacentries.log file.
#
#  Name: lclselog_move.pl
#
#  Rem:
#
#  Facility:  SLAC
#
#  Auth: 31-Oct-2008, Debbie Rogind (drogind); modified from original 
#                     code by Koosh.
#  Rev:  dd-mmm-yyyy, Reviewer's Name    (USERNAME)
#  Auth: 16-Sep-2014, Shahsi Divekar (divekar);  modified
#--------------------------------------------------------------
#
use File::Copy;
use File::Path;

#
# Specify constants used for processing.
#

$delay_secs = 8;
$max_files_processed_per_loop = 5;
$debug = 0;
 
if ($ARGV[0] =~ m/-debug/i) 
{
    $debug = 1;
}
  
     
print "lclselog_move.pl '-debug' switch = ".$debug."\n";
print "Logging is directed to ENV(PHYSICS_DATA)/logbook/log/lclselog_move.log\n";

while (1)
{

# sleep
sleep($delay_secs);

# now process a fixed number of file (sets)
$date = readpipe("date");

$year = readpipe("date +%Y");
@lines = split /\cJ/, $year;
$year = $lines[0];
#if ($debug) {
#  print "year: ".$year."\n";
#}

$month = readpipe("date +%m");
@lines = split /\cJ/, $month;
$month = $lines[0];
#if ($debug) {
#  print "month = ".$month."\n";
#}

$day = readpipe("date +%d");
@lines = split /\cJ/, $day;
$day = $lines[0];
#if ($debug) {
#  print "day = ".$day."\n";
#}

# dr took off +1 - was:(($dt->day_of_year)/7+1))
$weekofyear = readpipe("date +%V");
@lines = split /\cJ/, $weekofyear;
$weekofyear = $lines[0];
#if ($debug) {
#  print "week = ".$weekofyear."\n";
#}

$elogHost = "physics-elog:";

$d = "/var/www/lclselog/data/";

$destinationdir = $elogHost.$d.$year."/".$weekofyear."/".$day.".".$month."/";
$backupdir = $elogHost.$d."backup/";
# from directory:
$dir = $ENV{'PHYSICS_DATA'}."/logbook/data/";

$logdir = $ENV{'PHYSICS_DATA'}."/logbook/log/";

if ($debug) {
    print "root path for physics data dir: ".$dir."\n";
    print "root path for logbook: ".$logdir."\n";
    print "path for backupdir: ".$backupdir."\n";
    print "path for destinationdir: ".$destinationdir."\n";
}

@xmlfiles = ();
@lines;

@files;
@links;
@images;

$file;
$link;
$image;

$fileexists = 0;
$linkexists = 0;
$imageexists = 0;

#$ev = ">>".$d;
$ev = ">>".$logdir;
open (LOG, ">>$logdir/lclselog_move.log") || die ("Cannot open log file ".$logdir."slacentries.log - TERMINATING!\n");

#search for all xml files in the directory
opendir(DIR, $dir);
while($_ = readdir(DIR))
{
	if( $_ =~ /.xml$/)
	{
		push(@xmlfiles, $_);
	}
}
if ($debug) {
    for $j(@xmlfiles)
    {
	print "xmlfiles found: ".$j."\n";
    }
}

for ($x = 0; $x < scalar(@xmlfiles); $x++)
{
    if ($x ==$max_files_processed_per_loop ){
	 print LOG "break out of processing loop after ".$x." entries\n";
	 last; 
    }

    $xmlfile = @xmlfiles[$x];
      open INPUT, $dir.@xmlfiles[$x] or last;
      print LOG "\n".$date."\n"."Found ".@xmlfiles[$x]."\n";
     

	@lines = <INPUT>;
	@files = ();
	@links = ();
	@images = ();
	@author = ();
	@author2 = ();
	@category = ();
	@category2 = ();
	@title = ();
	@title2 = ();
	@isodate = ();
	@isodate2 = ();
	@severity = ();
	@severity2 = ();
	@keywords = ();
	@keywords2 = ();
	@metainfo = ();
	@metainfo2 = ();
	@text = ();
	@text2 = ();
	$imageexists = 0;
	$fileexists = 0;
	$linkexists = 0;

	for $j(@lines)
	{
		if ($j =~ m/^<file>/)
		{
			if (length($j) > 14)
			{
				push(@files, $j);
			}
		}
		if ($j =~ m/^<link>/)
		{
			if (length($j) > 14)
			{
				push(@links, $j);
			}
		}
		if ($j =~ m/^<image>/)
		{
			if (length($j) > 16)
			{
				push(@images, $j);
			}
		}
		if ($j =~ m/^<author>/)
		{
			push(@author, $j);
	    }
		if ($j =~ m/<\/author>/)
		{
			push(@author2, $j);
	    }
		if ($j =~ m/^<category>/)
		{
			push(@category, $j);
	    }
		if ($j =~ m/<\/category>/)
		{
			push(@category2, $j);
	    }
		if ($j =~ m/^<title>/)
		{
			push(@title, $j);
	    }
		if ($j =~ m/<\/title>/)
		{
			push(@title2, $j);
	    }
		if ($j =~ m/^<isodate>/)
		{
			push(@isodate, $j);
	    }
		if ($j =~ m/<\/isodate>/)
		{
			push(@isodate2, $j);
	    }
		if ($j =~ m/^<severity>/)
		{
			push(@severity, $j);
	    }
		if ($j =~ m/<\/severity>/)
		{
			push(@severity2, $j);
	    }
		if ($j =~ m/^<keywords>/)
		{
			push(@keywords, $j);
	    }
		if ($j =~ m/<\/keywords>/)
		{
			push(@keywords2, $j);
	    }
		if ($j =~ m/^<metainfo>/)
		{
			push(@metainfo, $j);
	    }
		if ($j =~ m/<\/metainfo>/)
		{
			push(@metainfo2, $j);
	    }
		if ($j =~ m/^<text>/)
		{
			push(@text, $j);
	    }
		if ($j =~ m/<\/text>/)
		{
			push(@text2, $j);
	    }
	}

	if ((@author && @author2 && @category && @category2 && @title && @title2 && @isodate &&
		 @isodate2 && @severity && @severity2 && @keywords && @keywords2 && @metainfo && @metainfo2 
		 && @text && @text2)eq 1)
	{
	   
		for $file(@files)
		{
			$file = substr($file, 6);
			$file = substr($file, 0, length($file)-8);
			if ($debug) {
			  print "File Found: ".$file."\n";
			  print "Directory ".$dir.$file."\n";
		        }   
			if (-e $dir.$file)
			{ 
                        if ($debug) {
                          print "File Exists\n\n";
		        }
			$fileexists++;		
			}
			else
			{
                            if ($debug) {				
                              print "File Does Not Exist\n\n";
                            }		
			}
		}				
		
		for $link(@links)
		{
			$link = substr($link, 6);
			$link = substr($link, 0, length($link)-8);
			if ($debug) {
			    print "1 Link Found: ".$link."\n";
			
			    print "Directory ".$dir.$link."\n";
			}
			if (-e $dir.$link)
			{
                           if ($debug) {
				print "Link Exists\n\n";
			    }
				$linkexists++;		
			}
			else
			{
                            if ($debug) {
				print "File Does Not Exist\n\n";
                            }		
			}
		}
		for $image(@images)
		{
			$image = substr($image, 7);
			$image = substr($image, 0, length($image)-9);
			if ($debug) {
			   print "1 Image Found: ".$image."\n";
			
			   print "Directory ".$dir.$image."\n";
		        }
			
			if (-e $dir.$image)
			{
                          if ($debug) {
				print "Image Exists\n\n";
			  }
				$imageexists++;		
			}
			else
			{
                           if ($debug) {
				print "File Does Not Exist\n\n";
                           }		
			}
		}
;
		if ((($linkexists && $fileexists) eq scalar(@links)) && (($linkexists && $fileexists) ne 0) || ( ($imageexists  eq scalar(@images)) && ($imageexists ne 0)))
		{
                    if ($debug) {
			print "Files exist...\n";

                    }
			 
			for $image(@images)
			{	    					
			    $copyfileone = $dir.$image;
			    $newfile = $destinationdir.$image;
			    $result = system("scp $copyfileone $newfile");
			    print LOG "scping ".$image." to ".$destinationdir." with status =".$result."\n";
			    if ($result==1) {
				if ($debug) {
				    print "Error: slacentries is terminating...scp to ".$destinationdir." failed\n";
				}
			    }

			}

			for $file(@files)
			{   					
			    $copyfileone = $dir.$file;
			    $newfile = $destinationdir.$file;
			    $result = system("scp $copyfileone $newfile");
                            print LOG "scping ".$file." to ".$destinationdir." with status =".$result."\n";
			    
			    if ($result==1) {
				if ($debug) {
				    print "Error: slacentries is terminating...scp to ".$destinationdir." failed\n";	     			    
				}
			    }
			}

			for $link(@links)
			{ 
			    $copyfileone = $dir.$link;
			    $newfile = $destinationdir.$link;
			    $result = system("scp $copyfileone $newfile");
                            
                            print LOG "scping ".$link." to ".$destinationdir." with status =".$result."\n";
			    
			    if ($result==1) {
				if ($debug) {
				    print "Error: slacentries is terminating...scp to ".$destinationdir." failed\n";	
				}		    
			    }
			}
			   
                        if ($debug) {
			   print "Copied files to ".$destinationdir."\n";
		        }
			# Now copy each file to the backup dir and then remove from $PHYSICS_DATA/logbook/data area	
			for $image(@images)
			{    
			    $copyfileone = $dir.$image;
			    $newfile = $backupdir.$image;
			    $result = system("scp $copyfileone $newfile");
                            
			    print LOG "scping ".$image." to ".$backupdir." with status = ".$result."\n";
			    

                            if ($result==1) {
				if ($debug) {
				    print "Error: slacentries is terminating...scp to ".$backupdir." failed\n";
				}	
			    }
			    $result=system("rm $copyfileone");
			    print LOG "rming ".$copyfileone."\n";
			    
               		    if ($result==1) {
				if ($debug) {		
				    print "Error: slacentries is terminating...removal of ".$copyfileone." failed\n";
				}
			    }
			}
			
			for $file(@files)
			{ 
			    $copyfileone = $dir.$file;
			    $newfile = $backupdir.$file;
			    $result = system("scp $copyfileone $newfile");

			    print LOG "scping ".$file." to ".$backupdir." with status = ".$result."\n";	
			    if ($result==1) {
				if ($debug) {	
				    print "Error: slacentries is terminating...scp to ".$backupdir." failed\n";
				}
			    }
			    $result=system("rm $copyfileone");
			    print LOG "rming ".$copyfileone."\n";
			    if ($result==1) {
				if ($debug) {
				    print "Error: slacentries is terminating...removal of ".$copyfileone." failed\n";
				}
			    }
			}

			for $link(@links)
			{
			    $copyfileone = $dir.$link;
			    $newfile = $backupdir.$link;
			    $result = system("scp $copyfileone $newfile");
			    print LOG "scping ".$link." to ".$backupdir." with status = ".$result."\n";	
			    if ($result==1) {
				if ($debug) {
				    print "Error: slacentries is terminating...scp to ".$backupdir." failed\n";
				}
			    }
			    $result=system("rm $copyfileone");
			    print LOG "rming ".$copyfileone."\n";
			    if ($result==1) {
				if ($debug) {
				    print "Error: slacentries is terminating...removal of ".$copyfileone." failed\n";
				}
			    }
			    	
			}
		        if ($debug) {
			    print "Copied files to ".$backupdir."and then removed \n";
			}

			$copyfileone = $dir.$xmlfile;
			$newfile = $backupdir.$xmlfile;
			$result = system("scp $copyfileone $newfile");
			print LOG "scping ".$xmlfile." to ".$backupdir." with status = ".$result."\n";
			if ($result==1) {
			    if ($debug) {
				print "Error: slacentries is terminating...scp to ".$backupdir." failed\n";
			    }	
			}
			$newfile = $destinationdir.$xmlfile;
			$result = system("scp $copyfileone $newfile");			
			print LOG "scping ".$xmlfile." to ".$destinationdir." with status = ".$result."\n";	
			if ($result==1) {
			    if ($debug) {
				"Error: slacentries is terminating...scp to ".$destinationdir." failed\n";
			    }	 
			}
			$result=system("rm $copyfileone");
			print LOG "rming ".$copyfileone."\n";
			if ($result==1) {
			    if ($debug) {
				print "Error: slacentries is terminating...removal of ".$copyfileone." failed\n";
			    }
			}


		}   
		else 
		    # this is a simple entry with no (aux files and links) or images, etc

		{
			for $link(@links)
			{
				print LOG "Error scping ".$link." to destination directory\n";
			}
			for $file(@files)
			{
				print LOG "Error scping ".$file." to destination directory\n";
			}
			for $image(@images)
			{
				print LOG "Error scping ".$image." to destination directory\n";
			}
			# move the xml file to the backup dir
			$copyfileone = $dir.$xmlfile;
			$newfile = $backupdir.$xmlfile;
			$result = system("scp $copyfileone $newfile");
			print LOG "scping ".$xmlfile." to ".$backupdir." with status = ".$result."\n";
			if ($result==1) {
			    if ($debug) {
				print "Error: slacentries is terminating...scp to ".$backupdir." failed\n";
			    }	
			}
			# move the xm file to the data dir to be picked up by browser
			$newfile = $destinationdir.$xmlfile;
			$result = system("scp $copyfileone $newfile");			
			print LOG "scping ".$xmlfile." to ".$destinationdir." with status = ".$result."\n";	
			if ($result==1) {
			    if ($debug) {
				print "Error: slacentries is terminating...scp to ".$destinationdir." failed\n";
			    }	 
			} 
			$result=system("rm $copyfileone");
			print LOG "rming ".$copyfileone."\n";
			if ($result==1) {
			    if ($debug) {
				print "Error: slacentries is terminating...removal of ".$copyfileone." failed\n";
			    }
			}

			
		}
	}
	else
	{
		# malformed xml file

		$copyfileone = $dir.$xmlfile;
		if ($debug) {
		    print "Error: slacentries found mal-formed xml file = ".$copyfileone."\n";
		} 
		print LOG  "Error: slacentries found mal-formed xml file = ".$copyfileone."\n"; 
		$bad = "_bad";
		#rename($xmlfile, $xmlfile.$bad) || die ( "Error in renaming" );	
		rename($copyfileone, $copyfileone.$bad) || die ( "Error in renaming" );
		next;
	}	
}
close (LOG);

}
