#!/usr/bin/perl 

##############################################################
# Description:
# This is File Replacement patch (un)installation script.
# It unpacks FRU file to the / directory and saves changes
# To the $dir_fru directory
#
# Input: 0 - -in to install
#            -out to uninstall
#        1 - FRU file name
#
# Output: Returns $ERROR if (un)installation is broken.
#                 $OK othervise
#
# Author:
# Ilya Teterev
##############################################################

use lib "/opt/nortel/base/lib/";

use warnings;
use strict;

use patchutil::patches_public;
use patchutil::patches_target;
use common_variables;
use baselog;
use DB_File;
use base_system;

our $operation = undef;  #Link to execution procedure
our $target    = undef;  #Target FRU file
our @content   = ();     #FRU file content
my %map_fru  = ();       #Installed files DB
my %map_perm = ();       #File permissions DB

#New file permissions
our $newowner = $NORTEL_UID;
our $newgid   = (getpwuid($NORTEL_UID))[3];
our $filemod  = 0660;
our $dirmod   = 0770;

#Folder with FRU data
our $dir_fru = $PATCHDIR . "/fru";

#HASH map files for FRU content quick search
our $map_file  = $dir_fru . "/map_fru.db";
our $perm_file = $dir_fru . "/map_perm.db";

#This string will generate an exception when it will be used as file name
our $newstr = "|NEW|";

#Debug mode
our $DEBUG = $FALSE;

#Ignoring Ctrl-C signal to prevent the $map_file map corruption
$SIG{'INT'} = 'IGNORE';

sub dprint
{
   print "DEBUG: ", join "##", @_, "\n" if ($DEBUG);
}

sub EXIT
{

   #Closing work files
   map_close() if (tied(%map_fru));
}

exit(main());

sub service_in;
sub service_out;

# Name: usage
# Description: prints usage string
# Output: usage string
sub usage
{
   print "usage: $0 -<in|out> <FRU file>\n";
}

# Name: map_open
# Description: establishes a link between the %map_fru and the $map_file
# Output: n/a
sub map_open
{
   dprint($map_file);
   tie %map_fru, 'DB_File', $map_file, O_RDWR | O_CREAT, 0666, $DB_HASH
     or die "Can't open map file";
   tie %map_perm, 'DB_File', $perm_file, O_RDWR | O_CREAT, 0666, $DB_HASH
     or die "Can't open map file";
} ## end sub map_open

# Name: map_close
# Description: drops a link between the %map_fru and the $map_file
# Output: n/a
sub map_close
{
   untie(%map_fru);
   untie(%map_perm);
}

# Name: content_get
# Description: Fills the @content with FRU data
# Output: n/a
sub content_get
{
   @content =
     map {"/" . $_}
     split(/\n/, qx#$TAR tvf $target \| $AWK '{ print \$6 }' #);
   dprint("content:", @content);
} ## end sub content_get

# Name: do_backup
# Description: Performs previous data backup
# Input/output: $FALSE on error, $TRUE otherwise
sub do_backup
{
   my $elem     = undef;
   my $cmdstr   = undef;
   my $archloc  = undef;
   my $archperm = undef;
   my ($fmode, $fuid, $fgid) = ();

   foreach $elem (@content)
   {

      #Update permissions map for existing directories
      if (-d $elem)
      {
         ($fmode, $fuid, $fgid) = (stat($elem))[2, 4, 5];
         $fmode &= 07777;                  #Store permissions only
         $archloc  = $dir_fru . $elem;     #For archive cleanup
         $archperm = "$fmode+$fuid+$fgid";
      } ## end if (-d $elem)
      elsif (-e $elem)
      {
         ($fmode, $fuid, $fgid) = (stat($elem))[2, 4, 5];
         $fmode &= 07777;                  #Store permissions only
         # "-p" will allow to maintain the file timestamp of the file as well
         $cmdstr = "$CP -p --parents $elem $dir_fru";
         dprint($cmdstr);
         system $cmdstr;

         #Error checking
         return $FALSE if ($?);
         $archloc  = $dir_fru . $elem;
         $archperm = "$fmode+$fuid+$fgid";
      } ## end elsif (-e $elem)
      else
      {

         #This record will call an exception if
         #it will be used somethere without checks
         $archloc  = $newstr;
         $archperm = $newstr;
      } ## end else [ if (-d $elem)
      dprint("map:",  $elem, $archloc);
      dprint("perm:", $elem, $archperm);

      #Update backup map
      #Skip existing directories
      if ((!-e $elem) or (!-d $elem))
      {
         $map_fru{$elem} = $archloc;
      }
      $map_perm{$elem} = $archperm;
   } ## end foreach $elem (@content)
   return $TRUE;
} ## end sub do_backup

# Name: do_restore
# Description: Restores data from backup
# Input/output: $FALSE on error, $TRUE otherwise
sub do_restore
{
   my $elem    = undef;
   my $cmdstr  = undef;
   my $archloc = undef;
   my $oldelem = undef;
   my @direlem = ();    #Directories to remove(if empty)

   foreach $elem (@content)
   {
      $oldelem = $map_fru{$elem};

      #Continue execution if the directory is not mapped
      #(All root directories are not included in map
      # Because they don't need to be removed)
      next if ($elem =~ /\/$/ and !defined($oldelem));

      if ($oldelem eq $::newstr)
      {
         if (-d $elem)
         {
            push @direlem, $elem;
         }
         else
         {
            unlink $elem;
         }
      } ## end if ($oldelem eq $::newstr...
      else
      {
         if (-d $oldelem)
         {
            push @direlem, $oldelem;
         }
         else
         {

            #Replacing the element with the old one
            $cmdstr = "$MV $oldelem $elem";
            system $cmdstr;

            #Error checking
            return $FALSE if ($?);
         } ## end else [ if (-d $oldelem)
      } ## end else [ if ($oldelem eq $::newstr...

      #Removing entry from backup map
      dprint("unmap:", $elem, $map_fru{$elem});
      delete $map_fru{$elem};
   } ## end foreach $elem (@content)

   if (scalar(@direlem))
   {

      #Sort directories (children will be removed before they parents)
      #And remove empty dirs
      rmdir foreach (sort {length($b) <=> length($a)} @direlem);
   } ## end if (scalar(@direlem))
   return $TRUE;
} ## end sub do_restore

# Name: apply_perm
# Description: Changes permission after installation/restore
# Input/Output: n/a

sub apply_perm
{
   my $elem = undef;
   foreach $elem (@content)
   {
      if (-e $elem)
      {
         my $oldperm = $map_perm{$elem};
         my ($fmode, $fuid, $fgid) = ();

         #Continue execution if the directory is not mapped
         #(All root directories are not included in map
         # Because they don't need to be removed)
         next if ($elem =~ /\/$/ and !defined($oldperm));

         if ($oldperm eq $newstr)
         {
            $fuid = $newowner;
            $fgid = $newgid;
            if (-d $elem)
            {
               $fmode = $dirmod;
            }
            else
            {
               $fmode = $filemod;
            }
            print "Warning: installing a new file. Please pay attention to the $elem file attributes\n";
         } ## end if ($oldperm eq $newstr...
         else
         {
            ($fmode, $fuid, $fgid) = split /\+/, $oldperm;
         }
         chown $fuid, $fgid, $elem;
         chmod $fmode, $elem;
      } ## end if (-e $elem)
   } ## end foreach $elem (@content)

   #update permissions and ownership of work directory
   
   unless (do_system([$CHMOD, '-R', '774', $dir_fru]))
   {
      baselog($LOG_ERROR, "Failed to chmod 770 $dir_fru folder.");
      return $ERROR;
   }
   unless (do_system([$CHOWN, '-R',  "$NORTEL_ACCT:$GROUPS{'patchadmin'}",  $dir_fru]))
   {
      baselog($LOG_ERROR, "Failed to chown $NORTEL_ACCT:$GROUPS{'patchadmin'} $dir_fru folder.");
      return $ERROR;
   }
} ## end sub apply_perm

# Name: check_cli
# Description: Checks command line input
# Input: command line parameters
# Output: $FALSE on error $TRUE otherwise
sub check_cli
{
   my $actioncode = undef;  #$ARGV[0]

   #Checking arguments number
   if (scalar(@ARGV) < 2)
   {
      usage();
      return $FALSE;
   }

   #Checking target file
   unless (-e $ARGV[1])
   {
      baselog($LOG_ERROR, "File not found: $ARGV[1]\n", $TRUE);
      return $FALSE;
   }
   $target = $ARGV[1];

   #Checking action
   $actioncode = $ARGV[0];
   $actioncode =~ tr/A-Z/a-z/;
   if ($actioncode =~ /^-in$/)
   {
      $operation = \&service_in;
   }
   elsif ($actioncode =~ /^-out$/)
   {
      $operation = \&service_out;
   }
   else
   {
      usage();
      return $FALSE;
   }
   return $TRUE;
} ## end sub check_cli

# Name: service_in
# Description: puts patch in-service
# Output: returns $TRUE if file is installed
#                 $FALSE otherwise
sub service_in
{
   my $cmdstr = undef;

   content_get();

   #Perform backup
   if (!do_backup())
   {
      baselog($LOG_ERROR, "Can't perform patch backup.");
      return $FALSE;
   }

   #Perform patch installation
   $cmdstr = "$TAR -xf $target -C /";
   system $cmdstr;
   if ($?)
   {
      baselog($LOG_ERROR, "Can't install the patch content.");
      return $FALSE;
   }

   #Modify files permissions
   apply_perm();

   return $TRUE;
} ## end sub service_in

# Name: service_out
# Description: removes patch from service
# Output: returns $TRUE if file is installed
#                 $FALSE otherwise
sub service_out
{

   content_get();

   #Restore archived data
   if (!do_restore())
   {
      baselog($LOG_ERROR, "Can't perform patch restore.");
      return $FALSE;
   }

   #Modify files permissions
   apply_perm();

   #Remove patch permissions data
   delete $map_perm{$_} foreach (@content);

   return $TRUE;
} ## end sub service_out

sub main
{

   #Create work directory
   if (!-d $dir_fru)
   {
      if (system("$MKDIR -p $dir_fru") != 0)
      {
         baselog($LOG_ERROR, "Failed to create $dir_fru folder.");
         return $ERROR;
      }
      if (system("$CHMOD 770 $dir_fru") != 0)
      {
         baselog($LOG_ERROR, "Failed to chmod 770 $dir_fru folder.");
         return $ERROR;
      }
      if (system("$CHOWN  $NORTEL_ACCT:$NORTEL_GRP  $dir_fru") != 0)
      {
         baselog($LOG_ERROR, "Failed to chown $NORTEL_ACCT:$NORTEL_GRP $dir_fru folder.");
         return $ERROR;
      }
   }

   #Exit if parameters are not correct
   return $ERROR unless check_cli();

   #Open work files
   map_open();

   #Calling operation
   return !&$operation();
} ## end sub main

