#!/usr/bin/perl -sw
$version = "1.02";
# Created by Steve Voisey (srv) 30 Nov 2010.
# email: [steve.voisey@ericsson.com]
#
# name: restoreConfig.pl

# Check for 'rpmsave' copies of each file listed in the input file list:
# For each found, show differences with newly installed version,
# and optionaly, restore the original.

# perl ./restoreConfig.pl -file=configFiles.list -update=yes

use File::Copy;
use Time::Local;

use constant FGMTDATE   => 0;
use constant FGMTTIME   => 1;
use constant FLOCALDATE => 2;
use constant FLOCALTIME => 3;
use constant FGMTOFFSET => 4;
use constant FLEVEL     => 5;
use constant FCOMPONENT => 6;
use constant FTEXT      => 7;
use constant FNUMBER    => 8;

my $filePath = "/opt/tandbergtv/cms/";

# Get the new date and time. Don't bother with seconds, the fraction gets stripped off and we need this.
  # We will just use the original seconds value.
  # ($tmp,$tmpmin,$tmphour,$tmpmday,$tmpmon,$tmpyear,$tmp,$tmp,$tmp) = localtime();
  ($tmp,$tmp,$tmp,$tmpmday,$tmpmon,$tmpyear,$tmp,$tmp,$tmp) = localtime();

  # Format the date and time with the correct number leading zeros etc.
  $date =  sprintf("%02d",($tmpmday)) . "-" . sprintf("%02d",($tmpmon + 1)) . "-" . sprintf("%04d",($tmpyear + 1900));
  # $newTime =  sprintf("%02d", $tmphour) . ":" . sprintf("%02d", $tmpmin) . ":" . sprintf("%06.3f", $logTime[2]);


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

$divide = "=" x 80 . "\n";
# Keep track of files processed, used to generate a counter token, default start at zero.
$counter = 0;

# Just display but not actually change any files, or go for it?
# Default, just display.
unless (defined($update)) { $update = "no"; }

# Need a list of files to process.
# If we have been given an input file, check that it exists.
if (defined($file)) {
    unless (-f $file)       { die "invalid file: $file"; }
}

# Otherwise, make a list of all files found under filePath.
# "sed -i s/$key/$tokenHash{$key}/g $configFile"
unless (defined($file)) {
    print "Save files found:\n\n" . `find $filePath -name *.rpmsave`;
    @fileList = `find $filePath -name *.rpmsave | sed s/\.rpmsave//g`;
} else {
    unless (open (FILE, "<$file"))   { die "cannot open $file $!"; }
    @fileList   = <FILE>;
    close FILE;
}

restoreFiles(\@fileList);

exit;


sub restoreFiles{
    my $fileArrayRef = $_[0];
    my $file;
    my @tmp = ();
    foreach $line (@$fileArrayRef) {
        # Not strictly applicable here, but allow us to read multi column files if required.
        @tmp = split ("!", $line, 2);
        $file = $tmp[0];
        # Drop the comments.
        if ($file =~ /^#/) { next; }
        # Drop any blank lines.
        if ($file =~ /^\s*$/) { next; }
        $counter++;
        chomp($file);
        #print "\n${divide}file: $file\n";
        # Check it exists.
        unless ( -f $file ) { print "\n$divide  ERROR: File not exist: $file\n"; next; }
        # Check for rpm backup file. rpmsave
        unless ( -f "${file}.rpmsave" ) { next; }
        print "\n${divide}";
        print "FILE:  $file\n";
        print "SAVED: ${file}.rpmsave\n";
        print "DIFFERENCES:\n";
        print `diff $file ${file}.rpmsave`;
        $diffStat = `diff $file ${file}.rpmsave`;
        if (($diffStat) && ( $update =~ /yes/i) && (verifyRestore($file))) {
           print "\n";
           #print `ls -al $file`;
           print "\ncopy $file $file.ORIGINAL-${date}\n";
           copy($file, "$file.ORIGINAL-${date}") or die "File cannot be copied.";
           print "\ncopy ${file}.rpmsave $file\n";
           copy("${file}.rpmsave", $file) or die "File cannot be copied.";
           #print `ls -al $file`;
        }
    }
}

sub verifyRestore {
    my $file = $_[0];
    while (1) {
        print "\nDo you want to restore [$file]? [yes|no]\n";
        my $answer=<STDIN>;
        chomp $answer;
        if ( $answer =~ /y.*|n.*/i) {
            if ($answer =~ /y.*/i) { return 1; }
            if ($answer =~ /n.*/i) { return 0; }
        }
        print "Invalid response: [$answer]\n";
    }
}




sub help {

$helpText1 = <<ENDHELPPAGE1;

  Check for 'rpmsave' copies of each file listed in the input file list.
  If no list is specified, search for ALL 'rpmsave' files
  found under $filePath

  For each file found, show differences with newly installed version,
  and optionaly, restore the original.

  Currently, this will ONLY work on UNIX/Linux
  Usage:

     > ./restoreConfig.pl -file=configFiles.list -update=yes

  Where:





  Function:

  Substitute a list of TOKENS for values in each file listed in the input file list.

      -help     : print this help text.



      -file.list  : Each line contains a file name to process.

                    Note: Will work on same file structure as 'subToken.pl' but simply
                    ignore anything on a line after the '!' character.

      -update     : value [yes|no]
                    yes - Replace the newly deployed file, with the original 'rpmsave' version.
                    default [no]


ENDHELPPAGE1

$continueMsg = "Enter any key to continue\n";

print $helpText1, $continueMsg;
$continue=<STDIN>; $continue = $continue;
}

sub history {
$historyText = <<ENDHISTORY;

 Created by steve.voisey\@ericsson.com 30th November 2010.

 Current Version: $version

 Check for 'rpmsave' copies of each file listed in the input file list:
 For each found, show differences with newly installed version,
 and optionaly, restore the original.


 History

 date     author   id   description
 -------- -------- ---  ----------------------------------------------------------
 30/11/10 srv      1.00 Created.
 22/12/10 srv      1.01 Added extra verification for replace.
 13/01/11 srv      1.02 Check return stat from diff and only prompt for update if different.
ENDHISTORY
print $historyText;
}


