#!/usr/bin/perl -w 
#
# Copyright (c) 2006 Zmanda Inc.  All Rights Reserved.
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 2 as published
# by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
# or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
# for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
#
# Contact information: Zmanda Inc, 505 N Mathlida Ave, Suite 120
# Sunnyvale, CA 94085, USA, or: http://www.zmanda.com
#
#

use lib "/usr/local/lib/mysql-zrm";
use lib '../lib';

package POC::Report;
BEGIN {
	my $module = "Data::Report";
	my $return = eval "use base qw($module)";
	if($@){
		die "Could not Load Module $module, please install the data::report module from MySQL ZRM \n";
    	}
}

package POC::Report::Text;
BEGIN {
    	my $module = "Data::Report::Plugin::Text";
    	my $return = eval "use base qw($module)";
    	if($@) {
       		die "Could not Load Module $module, please install the data::report module from MySQL ZRM \n";
    	}
}

package POC::Report::Html;
BEGIN {
    	my $module = "Data::Report::Plugin::Html";
    	my $return = eval "use base qw($module)";
    	if($@) {
       		die "Could not Load Module $module, please install the data::report module from MySQL ZRM \n";
    	}
}


use File::Spec::Functions;
use warnings;
use Getopt::Long;
use Time::Local;
use POSIX qw(strftime);
use Fcntl ':flock';

use XML::RSS;
use ZRM::Common;

my $LOGLOCATION;
my $INDEXLOCATION;
my $REPORTERCONFIGIFILE;
my $ZRMCONFIGFILELOCATION;
my $ZRMCONFIGFILE;
my $LS;
my $DEFAULTREPORTDIR;
my $HTML_REPORT_DIR;
my $DEFAULT_RSSFILE;

if ( !$onWindows ) {
	$LOGLOCATION               = "/var/log/mysql-zrm";
	$INDEXLOCATION             = "/var/lib/mysql-zrm";
	$REPORTERCONFIGIFILE       = "/etc/mysql-zrm/mysql-zrm-reporter.conf";
	$ZRMCONFIGFILELOCATION     = "/etc/mysql-zrm/";
	$ZRMCONFIGFILE             = "mysql-zrm.conf";
	$RSSTEMPLATEFILE           = "/etc/mysql-zrm/RSS.header";
	$LS                        = "ls -1";
	$DEFAULTREPORTDIR          = "./";
	$HTML_REPORT_DIR           = "./";
        $DEFAULT_RSSFILE            = "/usr/mysql-zrm";
} else {
	$LOGLOCATION               = $ZRM_HOME."\\var\\log\\mysql-zrm";
	$INDEXLOCATION             = $ZRM_HOME."\\var\\lib\\mysql-zrm";
	$REPORTERCONFIGIFILE       = $ZRM_HOME."\\etc\\mysql-zrm\\mysql-zrm-reporter.conf";
	$ZRMCONFIGFILELOCATION     = $ZRM_HOME."\\etc\\mysql-zrm\\";
	$ZRMCONFIGFILE             = "mysql-zrm.conf";
	$RSSTEMPLATEFILE           = $ZRM_HOME."\\etc\\mysql-zrm\\RSS.header";
	$LS                        = "dir /B";
	$DEFAULTREPORTDIR          = ".\\";
	$HTML_REPORT_DIR           = ".\\";
        $DEFAULT_RSSFILE            = "$ZRM_HOME\\usr\\lib\\mysql-zrm";
}

my $DEFAULTBACKUPINFO         = "backup-set,backup-date,backup-level,backup-status,backup-type,comment";
my $BACKUPSTATUSINFO          = "backup-set,backup-date,backup-level,backup-status,backup-type,comment";
my $BACKUPMETHODINFO          = "backup-set,raw-databases,raw-databases-snapshot,logical-databases";
my $BACKUPRETNTIONINFO        = "backup-set,backup-date,backup-level,backup-size,retention-policy";
my $BACKUPAPPPERFORMANCEINFO  = "backup-set,backup-date,backup-level,backup-size,backup-time,backup-type,read-locks-time,flush-logs-time";
my $BACKUPPERFORMANCEINFO     = "backup-set,backup-date,backup-level,backup-size,backup-size-compressed,backup-time,backup-type,compress-encrypt-time";
my $BACKUPRESTOREFULLINFO     = "backup-set,backup-date,backup-level,backup-directory,backup-status,comment";
my $BACKUPRESTOREINFO         = "backup-set,backup-date,incremental";
my $BACKUPREPLICATIONINFO     = "backup-set,backup-date,replication,slave-load-files";
my $BACKUPCLUSTERINFO         = "backup-set,backup-date,backup-status,ndb-connectstring,ndb-node-list,ndb-backup-id";

$logfile                      = catfile ($LOGLOCATION,"mysql-zrm-reporter.log");

my $indexFile                 = "index";

my $GREP                      = "grep -i";
my $TRUE                      = 1;
my $FALSE                     = 0;

my $DEFAULT_REPORT            = "backup-status-info";
my $RSSFILENAME               = "rss.xml";

$action="reporter";

my $readBackupSetConfigFile   = $FALSE;

my $directory;
my %opt;
my @configData;
my @rssChannelData;
my %RSSChannelData;

#Valid keys and display format
my %validIndexItems = (
	"backup-set"             => "15,<",
        "backup-date"            => "15,<,\%c",
        "mysql-version"          => "15,<",
        "backup-directory"       => "25,<",
        "backup-level"           => "12,<",
        "raw-databases"          => "14,<",
        "backup-time"            => "12,<",
        "backup-size"            => "12,<",
        "backup-status"          => "15,<",
        "raw-databases-snapshot" => "15,<",
        "raw-tables-snapshot"   =>  "10,<",
        "raw-tables"             => "10,<",
        "logical-databases"      => "17,<",
        "logical-tables"         => "15,<",
        "replication"            => "12,<",
        "slave-load-files"       => "16,<",
        "incremental"            => "12,<",
        "comment"                => "10,<",
        "read-locks-time"        => "15,<",
        "flush-logs-time"        => "15,<",
        "retention-policy"        => "16,<",
        "backup-size-compressed"  => "16,<",
        "compress"                => "16,<",
        "encrypt"                 => "16,<",
        "compress-encrypt-time"   => "20,<",
        "host"                    => "16,<",
        "innodb_data"             => "16,<",
        "innodb_logs"             => "16,<",
        "ndb-connectstring"       => "16,<",
        "ndb-node-list"           => "16,<",
        "ndb-backup-id"           => "16,<",
        "next-binlog"             => "16,<",
        "backup-type"             => "16,<"
);

        #Get the valid Fields list from referance hash
	my (@validOptions) = sort keys(%validIndexItems);

sub reporter_usage {
	if($_[0]) {
        	&printError( $_[0]."\n" );
         	print "$_[0]\n";
      	}
	print "USAGE :  \n";
	print "$0 \n";
	print "\t\t[--fields <name1,name2,name3 ... > ]  \n";
	print "\t\t[--destination <dir>]                 \n";
	print "\t\t[--where <fieldName=value>]           \n";
	print "\t\t[--show <backup-method-info | backup-status-info | backup-retention-info | \n";
	print "\t\t[       backup-performance-info | restore-info | selective-restore-info | \n";
	print "\t\t[       replication-info | backup-app-performance-info | backup-cluster-info>]  \n";
	print "\t\t[--type <html>]                      \n";
	print "\t\t[--output <file>]                    \n";
	print "\t\t[--latest                            \n";
	print "\t\t[--noheader                          \n";
	print "\t\t[--help ]                           \n\n";
	print "Valid field names are  : @validOptions \n\n";
	print "Please refer to mysql-zrm-reporter man page for more details\n\n";
}

sub checkIfExists {
        # check for dir name exists ,check for Dir if 2nd option is passed
	if( $_[1] ) {
      		if(-d $_[0]) {
         		return 0;
      		} else {
         		return 1;
      		}
  	} else {
        # check for File exists
      		if(-e $_[0]) {
         		return 0;
      		} else {
         		return 1;
      		}
  	}
}


sub validateCLI {
	my $param;
	$param = $_[0];

        foreach (@validOptions) {
        	if ($param  eq $_) {
                	return 0;
                }
        }
        return 1;
}

 sub my_top_heading {
	my $self = shift;
	$self->_print("\n");
	$self->_print("\n");
	$self->_print("            *********************************************************************\n");
	$self->_print("            *                                                                   *\n");
	$self->_print("            *        Z R M    B A C K U P  R E P O R T  F O R    M Y S Q L      *\n");
	$self->_print("            *                                                                   *\n");
	$self->_print("            *********************************************************************\n");
	$self->_print("\n");
	$self->_print("\n");
}



sub readConfigFile {
my %formatstr;

	if (-e $REPORTERCONFIGIFILE ) {
     		open(CONFIG,$REPORTERCONFIGIFILE) || &printAndDie("Can not open $REPORTERCONFIGIFILE file, $! \n");
	} else {
     		&printLog("Reporter configuration file not found, assigning default values \n");
     		return %validIndexItems;
   	}

   	(@configData) = <CONFIG>;
   	close CONFIG;

    	foreach  $line (@configData) {
      		chomp($line);
      		next if ($line =~ /^#/);
      		next if ($line =~ /^\s*$/);
      		next if ($line =~ /^\s*#/);
    		#$line =~ s/\s+//g;
      		($field,$formatStr) = split(/=/,$line);

      		if($field =~ /backup-date/) {
          		($width,$align,$optional1) = split(/,/,$formatStr);
          		$optional1 = "%c" if($optional1 eq "");
      		} else {
          		($width,$align) = split(/,/,$formatStr);
      		}

          	$field =~ s/\s+//g;
          	$width =~ s/\s+//g;
          	$align =~ s/\s+//g;

      		if ( $width !~ /\d+/ ) {
           		&printError("$field field width is not specified as Number,  default value 15 is assigned to this field \n");
           		$width = 15;
      		}

      		if($align !~ /[<|>]/) {
           		&printError("For $field alignment mode $align is not valid, only <,> are allowed, default value < is being assumed \n");
           		$align = "<";
      		}

      		if ($field =~ /backup-date/) {
		        $formatstr{"$field"} = "$width,$align,$optional1";
      		} else {
           		$formatstr{"$field"} = "$width,$align";
      		}
    	}
    	return %formatstr;
}

sub _top_heading {
	my $self = shift;
    	#my $type = shift;
    	if($reportType eq "HTML" ) {
       		$self->_print("<html>\n",
                "<head>\n",
                "<title>", "Z R M      B A C K U P      R E P O R T", "</title>\n",
                '<link rel="stylesheet" href="css/', $self->get_style, '.css">', "\n",
                "</head>\n",
                "<body>\n");

#                  "<p class=\"title\">", "ZRM TEST REPORT 1", "</p>\n",
#                  "<p class=\"subtitle\">", "ZRM TEST REPORT 2", "<br>\n",
#                  "ZRM TEST REPORT 3", "</p>\n");
	}
}

sub _std_stylist {
	my ($rep, $row, $col) = @_;

	return { line_after => 1 }
	if $row eq "total" && !$col;
    		return;
}

sub finish {
	my $self = shift;
	$self->_argcheck(0);
	$self->SUPER::finish;
	if($reportType eq "HTML" ) {
		$self->_print("<br>\n");
		$self->_print("<br>\n");
		$self->_print("</body>\n</html>\n");
    	}
}

 sub convertDate {
	my ($inputDate,$dateFormat) = @_;

        #Need To check the date format "20060909100108"
	my $year   = substr($inputDate,0,4);
	my $month  = substr($inputDate,4,2);
	my $day    = substr($inputDate,6,2);
	my $hr     = substr($inputDate,8,2);
	my $min    = substr($inputDate,10,2);
	my $sec    = substr($inputDate,12,2);

	my $epTime = timelocal($sec,$min,$hr,$day,$month-1,$year);
	chomp($epTime);
	$dateFormat =~ s/\"//g;
	$dateFormat =~ s/\'//g;
	my $dateConverted = strftime($dateFormat, localtime($epTime));

	return $dateConverted;
}




sub readHtmlReportProps {
#$_[0] : is the backup-set name this is optional, if not passed global mysql-zrm.conf is read
my $result;
my $name;
my @defaultConfigData;
my $configFilePath =  $ZRMCONFIGFILELOCATION;
	if( $_[0] ){
		$configFilePath = catfile( $configFilePath, $_[0] );
		if( ! -e $configFilePath ){
			$configFilePath =  $ZRMCONFIGFILELOCATION;	
		}
	}
	$configFilePath = catfile( $configFilePath, $ZRMCONFIGFILE );
	&readOptionsFile($configFilePath,\%configData);

	my $defaultConfigFilePath = catfile( $ZRMCONFIGFILELOCATION, $ZRMCONFIGFILE );
	&readOptionsFile($defaultConfigFilePath,\%defaultConfigData);

        if(exists $configData{"html-report-directory"}) {
		 $HTML_REPORT_DIR = $configData{"html-report-directory"};
	}elsif(exists $defaultConfigData{"html-report-directory"}) {
		 $HTML_REPORT_DIR = $defaultConfigData{"html-report-directory"};
	}else {
		 $HTML_REPORT_DIR = $DEFAULTREPORTDIR;
	}

        if(exists $configData{"html-reports"}) {
                 $HTML_REPORTS = $configData{"html-reports"};
	}elsif(exists $defaultConfigData{"html-reports"}) {
		 $HTML_REPORTS = $defaultConfigData{"html-reports"};
        }else {
                 $HTML_REPORTS = $DEFAULT_REPORT;
        }

        if(exists $configData{"webserver-url"}) {
                 $WEBSERVER_URL = $configData{"webserver-url"};
	}elsif(exists $defaultConfigData{"webserver-url"}) {
		 $WEBSERVER_URL = $defaultConfigData{"webserver-url"};
	}

        if(exists $configData{"rss-header-location"}) {
                 $RSSTEMPLATEFILE = $configData{"rss-header-location"};
	}elsif(exists $defaultConfigData{"rss-header-location"}) {
		 $RSSTEMPLATEFILE = $defaultConfigData{"rss-header-location"};
	}

        if(exists $configData{"destination"}) {
                 $DESTINATION = $configData{"destination"};
	}elsif(exists $defaultConfigData{"destination"}) {
		 $DESTINATION = $defaultConfigData{"destination"};
	}
}

sub createRSS {
my($action,$link) = @_;

$RSSChannelData{"title"}  = "Zmanda Recovery Manager Backup Reports for MySQL";
$RSSChannelData{"link"}   = " ";
$RSSChannelData{"description"} = "Reports Created by Zmanda Recovery Manager (ZRM) for MySQL";
$RSSChannelData{"subject"}     = "ZRM Software";
$RSSChannelData{"creator"}     = "www.zmanda.com";
$RSSChannelData{"publisher"}   = "www.zmanda.com";
$RSSChannelData{"managingeditor"} = "webmaster\@zmanda.com";
$RSSChannelData{"rights"} = "Copyright 2005, Zmanda.com";
$RSSChannelData{"language"} = "en-us";
$RSSChannelData{"updateperiod"} = "Daily";
$RSSChannelData{"updatefrequency"} = "1";

	my $date = `date -R`;
        chomp($date);

        my $titleTime = `date "+%r"`;
        chomp($titleTime);
        my $titleDate = `date "+%F"`;
        chomp($titleDate);

        $Item_Link    = "$WEBSERVER_URL"."$link";

   	&readRssTemplate;

        my $rss = new XML::RSS (version => '2.0');
        if ($action =~ /create/){
          	$rss->channel(
                	title        => $RSSChannelData{"title"},
                	link         => $RSSChannelData{"link"},
                	description  => $RSSChannelData{"description"},
                	dc => {
                        	date       => $date,
                        	subject    => $RSSChannelData{"subject"},
                        	creator    => $RSSChannelData{"creator"},
                        	publisher  => $RSSChannelData{"publisher"},
                        	managingEditor => $RSSChannelData{"managingeditor"},
                        	webMaster      => $RSSChannelData{"webMaster"},
                        	rights     => $RSSChannelData{"rights"},
                        	language   => $RSSChannelData{"language"},
                        	lastBuildDate => $date,
                	},
                	syn => {
                        	updatePeriod     => $RSSChannelData{"updateperiod"},
                        	updateFrequency  => $RSSChannelData{"updatefrequency"},
                        	updateBase       => $date,
                	},
          	);

        	$Item_Title = "Backup Report for MySQL ZRM at ".$titleTime." on ".$titleDate;
        	$Item_Description = $RSSChannelData{"description"}." at ". $date;

        	$rss->add_item(
                	title       => $Item_Title,
                	link        => $Item_Link,
                	description => $Item_Description,
                	dc => {
                		subject  => "$Item_Title",
                		creator  => $RSSChannelData{"creator"},
                	},
         	);
        	$rss->save("$RSSFILE");
        } else {
                my $rss = new XML::RSS;
                $rss->parsefile($RSSFILE);
                my $TmpRssFile = "/tmp/rss.tmp";

                $Item_Title = "Backup Report for MySQL ZRM at ".$titleTime." on ".$titleDate;
        	$Item_Description = $RSSChannelData{"description"}." at ". $date;
                $rss->add_item(title => $Item_Title,
                        link  =>  $Item_Link,
                	description => $Item_Description,
                        mode => 'insert'
                );
        	$rss->save("$TmpRssFile");
        	my $result = `mv $TmpRssFile $RSSFILE`;
        }
}

sub readRssTemplate {

	if($RSSTEMPLATEFILE) {
        	if(-e $RSSTEMPLATEFILE) {
               		open(RSSTEMPLATE,$RSSTEMPLATEFILE) || &printAndDie("Can not open $RSSTEMPLATEFILE file, $! \n");

       			(@rssChannelData) = <RSSTEMPLATE>;
        		close RSSTEMPLATE;

        		foreach my $line (@rssChannelData) {
                		$line =~ s/^\s*//;
                		next if($line =~ /^#/);
                		($tag,$tagvalue) = split(/=/,$line);

                		$tag = lc($tag);

               			$tag =~ s/^\s*//;
                		$tag =~ s/\s*$//;

                		$tagvalue =~ s/^\s*//;
                		$tagvalue =~ s/\s*$//;
                		$tagvalue =~ s/\"//g;

                		$RSSChannelData{$tag} = $tagvalue;
        		}

        	} else {

                	&printAndDie("RSS Template $RSSTEMPLATEFILE file not found, Generic RSS header template is found in /etc/mysql-zrm/RSS.header  user can copy and update it with customer specific information.\n");
        	}
	}
}

###############################   MAIN  #######################

	open (LOG, ">>$logfile") || die("ERROR: Cannot open logfile for writing: $!\n");

	my $ret = GetOptions (\%opt,"fields=s",
		   "destination=s",
		   "sort",
		   "where=s",
		   "show=s",
		   "type=s",
		   "output=s",
		   "latest",
		   "noheader",
		   "help"
	);

	unless ( $ret ) {
		&reporter_usage("");
		exit 1;
	}

      	if($opt{"help"}) {
        	&reporter_usage("");
        	exit 0;
      	}


      	#Validating --where input option.
      	#*************************************************#
      	#Get the key name value pairs to parse index files based on the requested Index field
      	if( $opt{"where"} ) {
         	my $optKeyValue = $opt{"where"};
         	($keyname,$keyvalue) = split(/=/,$optKeyValue);
         	if($keyvalue eq "") {
            		&reporter_usage("search value can not be blank, provide correct value ");
            		exit 1;
         	}
		$keyname =~ s/^\s+//;
        	$keyname =~ s/\s+$//;

        	$keyvalue =~ s/^\s+//;
        	$keyvalue =~ s/\s+$//;

        	if(&validateCLI($keyname)) {
        		&reporter_usage("Invalid Parameter $keyname, not a valid field name for Where option ");
            		exit 1;
        	}
        	if($keyvalue eq "") {
        		&reporter_usage("search value can not be blank, provide correct value ");
        		exit 1;
        	}
                if($keyname =~ /backup-set/i) {

			$readBackupSetConfigFile = $TRUE;
			$BACKUPSET = $keyvalue;

		}
      }
       if($readBackupSetConfigFile) {
                &readHtmlReportProps($keyvalue);
       } else {
                &readHtmlReportProps;
       }

       unless ( $opt{"destination"} ) {
                if(defined($DESTINATION)) {
			#$INDEXLOCATION = $DESTINATION;
                	$opt{"destination"} = "$DESTINATION";
		} else {
                	&printWarning("Backup root directory not specified, Assigning default value as $INDEXLOCATION \n");
                	$opt{"destination"} = "$INDEXLOCATION";
		}
       }

       unless ($opt{"fields"} || $opt{"show"}) {
               if($HTML_REPORTS) {
                        $opt{"show"} = $HTML_REPORTS;
               } else {
                        $opt{"fields"} =  $DEFAULTBACKUPINFO;
                        &printWarning("Backup info fields not specified, default displayed data set is $DEFAULTBACKUPINFO \n");
               }
       }

       if( $opt{"show"} ) {
		$showOption = $opt{"show"};
         	$showOption =~ s/^\s+//;
         	$showOption =~ s/\s+$//;

         	my(@tmpshow) = split(/,/,$opt{"show"});
         	foreach (@tmpshow) {
         		if ($_ =~ /backup-method-info/i) {
          			$Report{$_} = $BACKUPMETHODINFO;
         		}
         		elsif ($_ =~ /backup-status-info/i) {
          			$Report{$_} = $BACKUPSTATUSINFO;
         		}
         		elsif ($_ =~ /backup-retention-info/i) {
          			$Report{$_} = $BACKUPRETNTIONINFO;
         		}
         		elsif ($_ =~ /backup-performance-info/i) {
          			$Report{$_} = $BACKUPPERFORMANCEINFO;
         		}
         		elsif ($_ =~ /backup-app-performance-info/i) {
          			$Report{$_} = $BACKUPAPPPERFORMANCEINFO;
         		}
                        elsif ($_ =~ /selective-restore-info/i) {
                                $Report{$_} = $BACKUPRESTOREINFO;
         		}
                        elsif ($_ =~ /restore-info/i) {
                                $Report{$_} = $BACKUPRESTOREFULLINFO;
                        }
         		elsif ($_ =~ /replication-info/i) {
          			$Report{$_} = $BACKUPREPLICATIONINFO;
         		}
         		elsif ($_ =~ /backup-cluster-info/i) {
          			$Report{$_} = $BACKUPCLUSTERINFO;
         		}
         		else  {
            			&reporter_usage ("$_  invalid option for --show ");
            			exit 1;
         		}
		}
      	} else  {
		my(@tmpopts) = split(/,/,$opt{"fields"});

      		#Backup-set name is being appended to the list if it is not part of the requested fields
         	my(@return)   = grep(/backup-set/,@tmpopts);
         	if($#return < 0 ) {
           		push(@listopts,"backup-set");
         	}

         	foreach (@tmpopts) {
            		#remove leading and trailing white spaces if any
            		$_=~ s/^\s+//;
            		$_=~ s/\s+$//;
            		if(&validateCLI($_)) {
                		&reporter_usage("Invalid Parameter $_, not a valid field name");
                		exit 1;
            		}
           		push(@listopts,$_);
         	}

         	$Report{"fields"} =  join ',',@listopts;
	}

        $reportType = "TEXT";
      	if( defined $opt{"type"} && $opt{"type"} =~ /html/i) {
               	$reportType = "HTML";
		$HTML_REPORT_DIR  = catfile( $HTML_REPORT_DIR, "html" );
		if($WEBSERVER_URL && $RSSTEMPLATEFILE) {
			$GenRSS = $TRUE;
			$RSSFILE = catfile( $HTML_REPORT_DIR, $RSSFILENAME );
                }
        } else {
			$HTML_REPORT_DIR = catfile( $HTML_REPORT_DIR, "text" );
        }

	if($opt{"latest"}) {

      		$LATEST_ONLY = 1;
      	}
	if($opt{"noheader"}) {

      		$NOHEADER = 1;
      	}

      if($opt{"output"}) {
      		$fileName = $opt{"output"};
                $ReportFileName = $opt{"output"};
                if($HTML_REPORT_DIR) {
                        unless(-d $HTML_REPORT_DIR) {
                          my $result = `mkdir -p $HTML_REPORT_DIR`;
                        }
			$fileName = catfile( $HTML_REPORT_DIR, $fileName );
                }
            	unless (open($outfile,">$fileName")) {
                  	&printError("Can not open output file $fileName for writing");
                  	exit 1;;
            	}
      } else {
		$GenRSS = $FALSE;
      }

      #validating --destination input option
      #*************************************************#
      my $dirname = $opt{destination};
      $dirname =~ s/^\s+//;
      $dirname =~ s/\s+$//;

      if(&checkIfExists($dirname,"dir")){
      		&printError("Backup root directory $dirname not found");
             	exit 1;
      }
      #*************************************************#

      #Initialize fields with "-";
      my %initIndexItems;
      for (keys %validIndexItems) {
      		$initIndexItems{$_} = "----";
      }

      #Parse all the available Index files from the Backup root directory
      #Expected Dir Tree is $BackupRoot/<backupSet>/<TimeStamp>/index,

      if (defined($BACKUPSET)) {
		my $file = catfile( $dirname, $BACKUPSET );
	      		if(&checkIfExists($file,"dir")){
        	        	&printError("Backup Set directory $file not found");
                                exit 1;
			}
                
        	(@dirlist)  = $BACKUPSET;
      } else {
      	$dir_name ="\"$dirname\"";
        (@dirlist)  = `$LS $dir_name`;
      }

      foreach $dir (@dirlist) {
      		chomp($dir);
         	#Get the TimeStamp dir name, read index file from that location
                my @ts;
                if ( !$onWindows ) {
	         	(@ts) = `$LS $dirname/$dir`;
                } else {
                	my $path =  "$dirname\\$dir";
                        $path = "\"$path\"";
                    	(@ts) = `$LS $path`;
                }
          	foreach (@ts) {
             		chomp($_);
			$filename = catfile($dirname, $dir, $_, $indexFile);
             		if(&checkIfExists($filename)){
                		&printError("Missing file $filename, can not parse this index file \n");
                		next ;
             		}
             		unless (open(INDEX,"$filename")) {
                   		&printError("Can not open index file $filename\n");
                   		next;
             		}

             		my @tmparr = <INDEX>;
             		close(INDEX);
             		chomp (@tmparr);
             		my $var1;
             		my $hashname = "$dir"."$_";
             		for (keys  %initIndexItems) {
               			$hashname->{$_} = $initIndexItems{$_};
             		}
		     	#Build hash array list with names "<backupSet><TS>" and parse index file contents
		     	push(@HASHN,$hashname);
		     	foreach $var1 (@tmparr) {
				chomp($var1);
				my $v1;
				my $v2;
				($v1, $v2)=split("=",$var1);
                        	$v2 = "-----" if($v2 eq "");
				$hashname->{$v1}=$v2;
                     	}
          	}
          	undef(@ts);
      	}

      	%ConfigData = &readConfigFile;

# New format Code
#***************************

     	foreach $okey (sort keys %Report) {
      		(@listopts) = split(',',$Report{$okey});
		if($reportType eq "HTML" ) {
       		 	$rep = POC::Report::->create(type => "html");
     		} else {
        		$rep = POC::Report::->create(type => "text");
			$rep->set_heading(sub {}) if($NOHEADER);#overload set_heading to null
     		}

      		(@listopts) = split(',',$Report{$okey});
      		foreach $dir (@HASHN) {
			chomp($dir);
	  		if($opt{"where"}) {
                	 	next if ($dir->{$keyname} !~ /$keyvalue/);
          		}
              		foreach $name (@listopts) {
                    		push(@tmp,"$name=$dir->{$name}");
              		}

              		my $str=join '@@#@@',@tmp;
              		$TSHASH{$dir->{"backup-date"}} = $str;
              		undef @tmp;
      		}

     		#create Layout using the user selected index fields
     		$str = "([  " ;
     		foreach $key (sort keys(%TSHASH)) {
        		foreach $field (split (/@@#@@/,$TSHASH{$key})) {
              			my ($name,$values) = split(/=/,$field);
              			($fieldWidth,$fieldAlign) = split(/,/,$ConfigData{$name});
              			$name =~ s/-/_/g;
              			$str = $str."{ "."name => "."\"$name\"".", "."title => "."\"$name\"". ", "."width => $fieldWidth, "."align => \"$fieldAlign\" "."}, \n";
        		}
        		$str = "\$rep->set_layout\n"."$str"." ]);";
        		eval($str);
        		last;
    		}

     		#write output to file
     		if($outfile) {
        		$rep->set_output($outfile);
     		}

     		$rep->start();

                if($okey ne "fields" ){
                        if($reportType eq "HTML"){
                                $rep->_print("<h3>REPORT TYPE : $okey </h3>\n");
                        } else {
                                $rep->_print("\n");
                                $rep->_print("REPORT TYPE : $okey \n");
                                $rep->_print("\n");
                        }
                }

     		foreach $key (reverse sort keys(%TSHASH)) {
        		$str = "({ " ;
        		foreach $field (split(/@@#@@/,$TSHASH{$key})) {
               			my ($name,$value) = split(/=/,$field);
               			if ($name =~ /backup-date/) {
                   			($fieldWidth,$fieldAlign,$dateFor) = split(/,/,$ConfigData{$name});
                   			$dateRet = &convertDate($value,$dateFor);
                   			$value = $dateRet;
               			}

               			#Index Keys contains "-", reporter PM only takes alpha numericals and "_" as cel Name, need to handle this
               			$name =~ s/-/_/g;

               			$str = "$str"."\"$name\""." => "."\"$value\"".", ";
        		}
        		$str1 = "\$rep->add"."$str"."_style => "."\"normal\""." })";
        		eval($str1);
        		last if ($LATEST_ONLY);
     		}

     		$rep->finish;
                undef(@listopts);
                undef(%TSHASH);
  	}
        if($GenRSS) {
                if(-e $RSSFILE){
			&createRSS("add","$ReportFileName");
                } else {
			&createRSS("create","$ReportFileName");
 		}
        }
     	$rep->close;
     	close LOG;
     	exit 0;
