#!/usr/bin/perl

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

use warnings;
use strict;

use common_variables;
use baselog;

my $PatchAdapterPath = "/usr/local/taps/1.0/";

sub main;
sub bin_install;
sub bin_remove;

exit(main());

#main
#return 0: successful
#return !0: fail cause
sub main()
{
    my $rc = $OK;    
 
# dealing with argument 
    # it could be either 
    # binpatchutil -in PatchBody
    # binpatchutil -out PatchBody
    # binpatchutil -outall

    if ( ($#ARGV == 1) && 
         ($ARGV[0] eq "-in")  &&
         (-e $ARGV[1])
       )
    {
       # install the patch
       $rc = bin_install($ARGV[1]);
    }
    elsif ( ($#ARGV == 1) && 
              ($ARGV[0] eq "-out")
            )
    {
        # uninstall the patch
        $rc = bin_remove($ARGV[1]);
    }
    else
    {
        baselog($LOG_ERROR, "Incorrect parameters: @ARGV\n", $TRUE);
        $rc = $ERROR;
    } 

    return $rc;
}

sub bin_install
{
   my ($patch) = @_;
   my $id;
   my $rc = $OK;
   
   $id = $patch;
   $id =~ /^([\.\w\/]*\/)([\w_-]+)\.([bB][iI][nN])$/;
   $id = $PatchAdapterPath.$2;
  
   if(system("$CP -f $patch $id && $SYNC"))
   {
       baselog($LOG_ERROR, "Cannot install $patch to $id\n", $TRUE);
       $rc = $ERROR;
   }
   return $rc;
}

sub bin_remove
{
   my ($file) = @_;
   my $rc = $OK;
   
   if(!$file)
   {
      $rc = $ERROR;
   }
   else
   {
      $file =~ /^([\.\w\/]*\/)([\w_-]+)\.([bB][iI][nN])$/;
      $file = $PatchAdapterPath.$2;
      if(system("$RM -f $file && $SYNC"))
      {
          baselog($LOG_ERROR, "Cannot remove $file\n", $TRUE);
	  $rc = $ERROR;
      }
   }
   return $rc;
} 
