#!/usr/bin/perl -sw
#$version = "1.004";
#
# Created by Steve Voisey (srv) 23 may 2012.
# email: [steve.voisey@ericsson.com]
#
# name:  ingestTemplates.pl
#
# Script to manually ingest templates.
#
# Author  Date      Version Description
# srv     23/may/12 V1.000  Created
# srv     24/may/12 V1.001  Process unlisted templates as well, include help.
# srv     01/jun/12 V1.002  Only list remaining files with .xml extension.
# srv     02/jun/12 V1.003  Move failed template back to queue, for processing when CMS running.
# srv     03/jul/12 V1.004  Increase timeout from 20 seconds as insufficient for Rightv template 
#                           ingest at Orange during PPROD install.
#

use File::Copy;
use File::Basename;

$DIVIDE = "=" x 80 . "\n";

my $templateListFile = "templates.list";
my %propertiesHash;

if (defined($help))        { help(); exit;}

unless(defined($install))      { $install = "/opt/tandbergtv/cms/scripts/install"; }
unless(defined($home))         { $home = "/opt/tandbergtv/cms/workflow"; }

if(defined($file)) {
    unless( $file =~ /^\// )   { $file = "${install}/${file}"; }
}

if(defined($source)) {
    unless( $source =~ /^\// ) { $source = "${home}/${source}"; }
}

if(defined($destination)) {
    unless( $destination =~ /^\// ) { $destination = "${home}/${destination}"; }
}

unless(defined($file))         { $file = "$install/${templateListFile}"; }
unless(defined($source))       { $source = "$home/queue"; }
unless(defined($destination))  { $destination = "$home/templates"; }
unless(defined($wait))         { $wait = 2; }
unless(defined($limit))        { $waitLimit = 30; } else { $waitLimit = $limit; }

unless( -d $source ) { die "FATAL: Invalid directory source [$source]"; }
unless( -d $destination ) { die "FATAL: Invalid directory destination [$destination]";}
unless( -f $file ) { die "FATAL: Invalid file [$file]"; }

unless (open (FILE, "<$file"))   { die "FATAL: cannot open template list file [$file]"; }
@templateArray   = <FILE>;
close FILE;

ingestTemplate(\@templateArray, "$source", $destination, $wait, \%propertiesHash, $waitLimit);
unless(defined($propertiesHash{ingest})) { $propertiesHash{ingest} = "all" };

if($propertiesHash{ingest} =~ /all/i ) {
    # Have we got any templates left that were not in the list?
    @templateArray = ();
    @templateDir   = <$source/*.xml>;
    if( @templateDir > 0 ) {
        print "INFO: The following templates still need to be ingested\n\n";
        @templateDir = sort(@templateDir);
        foreach $element (@templateDir) {
            chomp($element);
            ($element) = fileparse($element);
            print "\ttemplate:  $element\n";
            push(@templateArray, $element);
        }
    
    
        print "\nINFO: Ingesting remaining templates now....\n\n";
        ingestTemplate(\@templateArray, $source, $destination, $wait, \%propertiesHash, $waitLimit);
    }
}

exit;

#####################################################################
# ingestTemplate
#####################################################################

sub ingestTemplate {
    my $templateArrayRef  = $_[0];
    my $source            = $_[1];
    my $destination       = $_[2];
    my $wait              = $_[3];
    my $propertiesHashRef = $_[4];
    my $waitLimit         = $_[5];
    
    my ($element, $action) = "";
    my ($count)   = 0;
    my @propertiesArray = ();
    
    foreach $element (@$templateArrayRef) {
        if( $element =~ /^\s+$/ ) { next; }
        if( $element =~ /^#/ )    { next; }
        if( $element =~ /^action:/ )    { 
            ($action) = $element =~ /^action:\s*(.*)$/ ;
            @propertiesArray = split(/,/, $action);
            returnPropertyHash( \@propertiesArray, $propertiesHashRef);
            print "\naction: ingest [ $propertiesHash{ingest} ]\n";
            next; 
        }
        
        print $DIVIDE;
        chomp($element);
        print "processing template [$element]\n";  
        unless( -f "${source}/${element}" ){ 
            print "\nWARNING: file not found!\n[${source}/${element}]\n"; 
            next;  
        }  
        print "moving ${source}/${element} --> ${destination}/${element}\n";
        move("${source}/${element}", "${destination}/${element}");
        # give it a second before proceeding.
        sleep(1);
    
        if( -f "${destination}/${element}" ) {
            for($count = 1; $count <= $waitLimit; $count++) {
            print "waiting $wait seconds for template ingest....\n";
            sleep($wait);
            unless( -f "${destination}/${element}" ) { last; }
            }
        }
        if( -f "${destination}/${element}" ) {
            print "\nFATAL: template failed to ingest! [${destination}/${element}]\n\n";
            print "restoring failed template to its original location\n";
            print "moving ${destination}/${element} --> ${source}/${element}\n\n";
            move("${destination}/${element}", "${source}/${element}");
            exit;
        } else {
            print "\nIngested successfully - template [${element}]\n\n";
        }
    }

}

###################################################################################
#  subroutine: returnPropertyHash                                                 
###################################################################################

sub returnPropertyHash  {
    my $propertiesArrayRef  = $_[0];
    my $propertiesHashRef   = $_[1];
    
    my ($line, $propertyName, $propertyValue) = "";
    
    foreach $line (@$propertiesArrayRef) {
        #chomp ($line);
        if ( $line =~ /^#/ )    { next; }
        if ( $line =~ /^\s*$/ ) { next; }
        if ( $line =~ /^.*=/i ) {
             ( $propertyName, $propertyValue ) = $line =~ /^(.*)\s*=\s*(.*)$/; 
             chomp($propertyValue);
             $$propertiesHashRef{$propertyName} = $propertyValue;
             #print "name [$propertyName] value [$propertyValue]\n";
             #print "hash [$$propertiesHashRef{$propertyName}]\n";
        }
    }
    return;
}

###################################################################################
#  subroutine: help
###################################################################################

sub help {

$helpText1 = <<ENDHELPPAGE1;

    Manually ingest templates contained in directory SOURCE in the order listed 
    in the file 'templates.list' by copying each template into directory DESTINATION.
    
    Any remaining templates, that are not listed in the file 'templates.list', are 
    copied last.
    
    After each template has been copied the script waits for CMS to ingest.
    
    If the template has not been ingested after n seconds, the script aborts.
    
    Example usage: 
    
        > ./ingestTemplate.pl
        
       -destination : value [directory]
                    Destination directory.
                    Watch directory CMS uses to ingest "templates".
                    default [/opt/tandbergtv/cms/workflow/templates]  
 
       -home     : value   [/path]
                    Default directory path of the CMS workflow directory.
                    default [/opt/tandbergtv/cms/workflow]  
                    
       -install  : value   [/path]
                    Default directory path of the "templates.list" file.
                    default [/opt/tandbergtv/cms/scripts/install]  

       -source   : value [directory]
                    Source directory.
                    Current location of the "templates" that need to be copied into 
                    destination.
                    default [/opt/tandbergtv/cms/workflow/queue]

       -wait     : value   [integer]
                    Number of seconds to wait for CMS to ingest a template.
                    After ( wait X limit ) the script aborts if the template has failed to 
                    ingest.
                    default [2]  
                    
       -limit    : value   [integer]
                    Number of times to wait for CMS to ingest a template.
                    After ( wait X limit ) the script aborts if the template has failed to 
                    ingest.
                    The default time allowed for a single template ingest is ( 2 X 30 ) = 60 seconds.
                    default [30]                  
ENDHELPPAGE1

print $helpText1;
}
#####################################################################
# end
#####################################################################
