#! /usr/bin/perl -w
###############################################################################
# Version 0.5 -- Oct 17, 2002
###############################################################################
#
# update_tbox
#
# This is an interactive script that finds all packages on the client's
# computer that need to be updated or installed, and gives them the option
# to do either an update or fresh install interactively or automatically.
# It downloads "serverlist" and "toolbox_dependencies" from the AIX Toolbox
# public site to figure out what is available and what dependencies
# are needed for each package. 
# It does not query or update packages from the crypto site, only the main
# AIX Toolbox site.
#
# wget is needed by the script; it exits if missing.
#
###############################################################################
# (C) COPYRIGHT International Business Machines Corp. 2002
# All Rights Reserved
#
# Disclaimer:  This is an unsupported, unwarranted script provided
# for the convenience of users of the 'AIX Toolbox for Linux Applications'.
# It will automatically download and install new RPMS on your system.
# Use at your own risk.
#
# No Warranty:
# THIS CODE IS PROVIDED BY IBM "AS IS." TO THE EXTENT PERMITTED BY APPLICABLE
# LAW, IBM MAKES NO WARRANTIES OR CONDITIONS EITHER EXPRESS OR IMPLIED,
# INCLUDING WITHOUT LIMITATION ANY WARRANTY OF NON-INFRINGEMENT AND THE
# IMPLIED WARRANTIES OF MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE
# REGARDING THE CODE OR TECHNICAL SUPPORT, IF ANY.
# 
# Limitation of Liability:
# NEITHER IBM NOR ITS SUPPLIERS ARE LIABLE FOR ANY DIRECT OR INDIRECT DAMAGES,
# INCLUDING WITHOUT LIMITATION, LOST PROFITS, LOST SAVINGS, OR ANY INCIDENTAL,
# SPECIAL, OR OTHER ECONOMIC CONSEQUENTIAL DAMAGES, EVEN IF IBM IS INFORMED OF
# THEIR POSSIBILITY. SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION OR
# LIMITATION OF INCIDENTAL OR CONSEQUENTIAL DAMAGES, SO THE ABOVE EXCLUSION OR
# LIMITATION MAY NOT APPLY TO YOU.
#
###############################################################################

use strict;

### Check for wget, exit if not installed
unless(`rpm -q wget`){
  die "\nYou need to download and install wget first.\nftp://ftp.software.ibm.com/aix/freeSoftware/aixtoolbox/RPMS/ppc/wget/\n\n";
}

### Clean up after unexpected exit
use sigtrap 'handler' => \&myhand, 'INT';
sub myhand{
  cleanup();
  exit;
}


###
### Global Values
###

my $url = "ftp://ftp.software.ibm.com/aix/freeSoftware/aixtoolbox/RPMS/ppc/";
my $importfile = "serverlist";   		
my $dependencyfile = "toolbox_dependencies";	
my $localname = "$$.locallist.txt";
my $servername = "$$.serverlist.txt";
my $diffname = "$$.diff.txt";
my %GLOBALhash;					###  Global hash to remove redundant terms
my %location;   				###  hash table for storing location of rpm's on ftp server
my $save = 0;					### -s 
my $query = 0;					### -q
my $all = 0;					### -a
my $down = 0;					### -d
my $lang = 0;					### -l
my $iterative = 0;				### -i
my $output = 0;					### -o
my $logname = "$$.logfile";
my $oslevel = `uname -rv`;			### Check for oslevel
chomp($oslevel);
$oslevel =~ s/(\d)\s(\d).*/$2.$1/;


###
### Main function calls
###
setargumentlist(@ARGV);

print "\n  Getting latest package information from server; Please wait...";
`wget ftp://ftp.software.ibm.com/aix/freeSoftware/aixtoolbox/data/$importfile >/dev/null 2>&1`;
print "..";
`wget ftp://ftp.software.ibm.com/aix/freeSoftware/aixtoolbox/data/$dependencyfile >/dev/null 2>&1`;
print ".\n";
my $a = `ls $importfile 2> /dev/null`;
my $b = `ls $dependencyfile 2> /dev/null`;
unless (($a) && ($b)){
  print "Couldn't download necessary files from server.\n";
  print "Please check your Internet connection or try again later.\n";
  cleanup();
  exit;
}

getlocallist($localname);
getserverlist($servername, $importfile);
my @difflist = getdiff($localname, $servername, $diffname);
getdependencies($url, $dependencyfile, @difflist);



#############################################
#	UIUPDATE
# Prints list of RPMS to install and prompts
# user for if they want the script to install
# all the scripts for them or if they want
# an interactive install to only install
# certain packages.
#############################################
sub uiupdate{
  my ($url, %hash) = @_;
  my ($pass, $i, $innerchoice, $choice, $key, @installedpackages, @previnstalledpackages);
  my $urllist = "$$.urllist";
  my ($oldrpm_to_update, $need_to_install, @osarray);
  
  if($output){
    open(LOG, ">$logname");
    print LOG "#" x 80, "\n";
    print LOG "#\tFollowing is a list of RPMs that are out of date.\t\t       #\n";
    print LOG "#\tAdditional dependency files may also have to be installed.\t       #\n";
    print LOG "#" x 80, "\n\n";
    print LOG "Out Of Date:\t\t\t\t\tUpdate:\n"; 
    print LOG "------------\t\t\t\t\t-------\n";
    close(LOG);
  }

  print "\n" x 25;
  print "#" x 80, "\n";
  print "#\tFollowing is a list of RPMs that are out of date.\t\t       #\n";
  print "#\tAdditional dependency files may also have to be installed.\t       #\n";
  print "#" x 80, "\n\n";

  print "Out Of Date:\t\t\t\t\tUpdate:\n"; 
  print "------------\t\t\t\t\t-------\n";
  @previnstalledpackages = `rpm -qa --queryformat "%{NAME}-%{VERSION}-%{RELEASE}.%{OS}.%{ARCH}.rpm-%{EPOCH}\n"`;
  undef %GLOBALhash;
  initializeglobalhash(@previnstalledpackages);

  ### Prints all out-of-date and missing items 
  foreach $key (sort keys %hash){
    ### Check to separate updates from fresh installs
    $oldrpm_to_update  = inlist(1, $key);
    $need_to_install = !inlist(0, $key);

    if($all){
      if (($need_to_install) && !($oldrpm_to_update)){
        $oldrpm_to_update = "Not Installed";
      }
      else{
        if(!($need_to_install)){
          $oldrpm_to_update = "";
        }
      }
    }

    ### Only print out the package with the correct os level
    if($oslevel =~ /5\.1/){
      @osarray = ("4.3");
    }
    elsif($oslevel =~ /^5/){
      @osarray = ("4.3", "5.1");
    }
    else{
      @osarray = ("");
    } 
 
    $_ = $key;
    /(.*\.aix)(\d\.\d)(.*)/;
    my $pre = $1;
    my $mid = $2;
    my $post = $3;

    if($mid == $oslevel){
      $pass = 1;
    }
    elsif($hash{$pre . $oslevel . $post}){
      $pass = 0;
    }
    else{
      while(@osarray){
        my $ostmp = pop(@osarray);
        if( $hash{$pre . $ostmp . $post}  ){
          if($ostmp == $mid){
            $pass = 1;
          }
          else{
            $pass = 0;
          }
          last;
        }
        $pass = 0;
      }
    }
    
    ### Check epoch for files with screwy release sequences, like openCIMOM
    if(($oldrpm_to_update) && ($oldrpm_to_update ne "Not Installed")){
      my $oldepoch = $oldrpm_to_update;
      $oldepoch =~ s/.*-(\(\w+\)$|\d+$)/$1/;
      $oldepoch =~ s/\(none\)/1/;
      my $newepoch = $key;
      $newepoch =~ s/.*-(\d+)$/$1/;
      if( $oldepoch > $newepoch){
        $pass = 0;
      }
    }

    ### Only process Language specific files if $lang(-l) is enabled.
    if( ((!$lang) && ($all)) && ( ($key =~ /\-i18n\-[A-Z]/) || ($key =~ /aspell\-\w\w\-/) ) ){
      $pass = 0;
    }
   
    ### Format/Print to screen all files available to be installed/updated
    if (($need_to_install) && ($oldrpm_to_update) && ($oldrpm_to_update !~ /.*ssl.*/) && ($pass)){   
      $oldrpm_to_update =~ s/(\.rpm)\-.*/$1/; 
      $key =~ s/(\.rpm)\-.*/$1/; 
      
      ### Optionally print to a log file
      if($output){
        open(LOG, ">>$logname");
        print LOG "$oldrpm_to_update\t\t$key\n";
        close(LOG);
      }

      if( (length $oldrpm_to_update) > 31){
        printf("%-20s\t\t%-20s\n", $oldrpm_to_update, $key);
      }
      elsif( (length $oldrpm_to_update) < 25){
        printf("%-20s\t\t\t\t%-20s\n", $oldrpm_to_update, $key);
      }
      else{
        printf("%-20s\t\t\t%-20s\n", $oldrpm_to_update, $key);
      }
    }
    ### If it can't be updated, delete it from the hash
    else{
      delete $hash{$key};
    }
  }  ## end foreach

  ###  printhashtable(%hash);

  ### If -q or --query is specified, don't download or install
  if($query == 1){
    cleanup();
    exit;
  }

  ### Exit if no packages are available
  unless(keys %hash){
    print "\nNo Packages Need To Be Updated At This Time.\n\n";
    cleanup();
    exit; 
  }
  
  ### UI prompt for type of install/download
  my $tmpword = $down ? "download" : "install"; 
  print "\n\nAutomatically ".  $tmpword ." available packages?\t(a)\n";
  print "Interactively ".  $tmpword . " available packages?\t(i)\n";
  print "Quit without " . $tmpword . "ing?\t\t\t(q)\n";
  print "Choice: ";

  $choice = <STDIN>;
  chomp($choice);
  print "\n";

  open(OUT, ">$urllist");

  ### Interactive Install
  if ($choice =~ /^i/i){

    foreach $key (sort keys %hash){
      if( $hash{$key} ){  ### check hash{key} bc we delete from hash
        $key =~ s/plus/\+/g;
        $_ = $key;
        s/-\d+$//;
        print "\n>Install $_?\n";
        $i = 0;
        if($hash{$key}[$i]){
          my $deplist = "";
          while($hash{$key}[$i]){
            if(!(inlist(0, $hash{$key}[$i]))) {
              $deplist = $deplist .  "\t\t$hash{$key}[$i]\n";
            }
            else{
              $hash{$key}[$i] = "NotHere"; ## Flag as already checked, no need to install
            }
            $i++;
          }
          $deplist =~ s/(.*\.rpm)\-\d+/$1/g;
          print "\tAnd Dependencies:\n" . $deplist unless !$deplist;
            
        }
        print "Choice = (y/n): ";
        $innerchoice = <STDIN>;
        chomp($innerchoice);
  
        ### User chose to install current package
        if ($innerchoice =~ /y/i){
          $i = 0;
          while($hash{$key}[$i]){
            if($hash{$key}[$i] ne "NotHere"){
              my $tmpstring =  installdependency($url, $key, $hash{$key}[$i], \@installedpackages, %hash);
              print OUT $tmpstring;
              $tmpstring =~ s/.*\/(.*)\s*/$1\:/m;
              my @tmpstringa = split /:/, $tmpstring;

              foreach(@tmpstringa){
                s/^\s+(\w.*\w)\s+$/$1/;
                s/\*//;
                delete $hash{$_};
              }

              $_ = $hash{$key}[$i]; 

              my $tmpoutelem = $hash{$key}[$i]; 
              $tmpoutelem =~ s/-\d+$//;
              print OUT $url . $location{$_} . "/" . $tmpoutelem . "*\n";
              pushtohash($hash{$key}[$i]);  
              my $tmphkey = $hash{$key}[$i];
              delete $hash{$tmphkey};
            }
            $i++;
          }
          my $tmpoutelem = $key;
          $tmpoutelem =~ s/-\d+$//;
          print "    Finding $tmpoutelem\n";
          print OUT $url . $location{$key} . "/" . $tmpoutelem . "\n";
          pushtohash($key);
          delete $hash{$key};
        }  ## end if innerchoice == i
        else{
          $key =~ s/-\d+$//;
          print "    Not installing $key\n";
        }
      } ## end outer if
    } ## end foreach
  } ## end choice == i

  ### Automatic Install
  elsif ($choice =~ /^a/i){
    foreach $key (sort keys %hash){

      if( (!(inlist(0, $key))) && ($hash{$key}) ){ ### check hash{key} bc we delete from hash in loop

        $key =~ s/plus/\+/g;

        print "    Finding all files: $key\n";
        my $keydir = $key;
        $keydir =~ s/\.aix.*//;
        pushtohash($keydir);  # ???
        pushtohash($key);
 
        $i = 0;
        while( $hash{$key}[$i] ){
          if( !(inlist(0, $hash{$key}[$i])) && !(inlist(0, $key)) ){
            print "    Finding dependency $hash{$key}[$i]\n"; 
            $_ = $hash{$key}[$i]; 
            my $tmpoutelem = $hash{$key}[$i];
            $tmpoutelem =~ s/-\d+$//;
            print OUT $url . $location{$_} . "/" . $tmpoutelem . "*\n";
            pushtohash( $hash{$key}[$i] );  
            my $tmphkey = $hash{$key}[$i];
            delete $hash{$tmphkey};
          }
          $i++;
        }
        my $tmpoutelem = $key;
        $tmpoutelem =~ s/-\d+$//;
        print OUT $url . $location{$key} . "/" . $tmpoutelem . "\n";
        delete $hash{$key};
      } 
    } ## end foreach
  } ## end elsif

  else{
    print "\n\nInvalid Option: $choice\n\n" unless ($choice =~ /^q/i); 
    cleanup();
    exit;
  }

  close(OUT);
  
  open(SESAME, "$urllist");


  if($iterative){
    while(<SESAME>){
      chomp($_);
      s/\+/plus/g;
      print "\n   *Downloading $_\n";
      if($output){ 
        `echo \"\n   *Downloading $_\n\" >> $logname`;
        `wget $_ 2>&1 | tee -a $logname`; 
      }
      else{ `wget $_ >/dev/null 2>&1`; }
      s/.*\/(.*)/$1/;   

      unless( $down ){
        if($output){
          open(LOG, ">>$logname");
          print LOG "\n\tAbout to Install $_\n";
          print LOG "\n\trpm -hUv $_\n";
          print "\n\tAbout to Install $_\n";
          print "\n\trpm -hUv $_\n";
          `rpm -hUv $_ 2>&1 | tee -a $logname`;
          print LOG "\n\tRemoving $_\n" unless ( ($save == 1) );
          print "\n\tRemoving $_\n" unless ( ($save == 1) );
          `rm $_ 2>&1 | tee -a $logname`  unless ( ($save == 1) );
          close(LOG);
        }
        else{
          print "\n\tAbout to Install $_\n";
          print "\n\trpm -hUv $_\n";
          `rpm -hUv $_`;
          print "\n\tRemoving $_\n" unless ( ($save == 1) );
          `rm $_`  unless ( ($save == 1) );
        }
      }
    }

  }
  else{
    my $rpms_to_install = "";
    while(<SESAME>){
      chomp($_);
      s/\+/plus/g;
      print "\n   *Downloading $_\n";
      if($output){ 
        `echo \"\n   *Downloading $_\n\" >> $logname`;
        `wget $_ 2>&1 | tee -a $logname`; 
      }
      else{ `wget $_ >/dev/null 2>&1`; }
      s/.*\/(.*)/$1/;   
      $rpms_to_install = $rpms_to_install .  $_ . " ";
    }
    unless(($down) || (!$rpms_to_install)){
      if($output){
        open(LOG, ">>$logname");
        print LOG "\n\n\tAbout to Install All Specified RPM Packages Using:\n";
        print LOG "\t\trpm -hUv filename.rpm\n\n";
        print LOG "\n\trpm -hUv $rpms_to_install\n";
        print "\n\n\tAbout to Install All Specified RPM Packages Using:\n";
        print "\t\trpm -hUv filename.rpm\n\n";
        print "\n\trpm -hUv $rpms_to_install\n";
        `rpm -hUv $rpms_to_install 2>&1 | tee -a $logname`;
        close(LOG);
      }
      else{
        print "\n\n\tAbout to Install All Specified RPM Packages Using:\n";
        print "\t\trpm -hUv filename.rpm\n\n";
        print "\n\trpm -hUv $rpms_to_install\n";
        `rpm -hUv $rpms_to_install`;
      }
    }
  
    if($output){
      `rm $rpms_to_install 2>&1 | tee -a $logname`  unless (($save == 1) || (!$rpms_to_install));
    }
    else{ 
      `rm $rpms_to_install`  unless (($save == 1) || (!$rpms_to_install));
    }
  }

  close(SESAME);
  cleanup();
  print "\n\n";

}  ## end uiupdate



#################################################
#	INSTALLDEPENDENCY			#
# Recursively finds and installs all 		#
# dependencies of the dependencies already	#
# set to install.				#
# Returns full path name of files to install	#
# printed to urllist.				#
#################################################
sub installdependency{
  my ($url, $key, $dep, $ip, %hash) = @_;
  print "    Finding $dep\n";
  my $i = 0;
  my @curip;
  for($i=0; $i<@$ip; $i++){
    $curip[$i] = $ip->[$i];
  }
  push @curip, "NotHere";
  my @iarray;
  my $ret = "";
  my @previp = `rpm -qa`;
  push @previp, "NotHere";
  pushtohash("NotHere");
  $i = 0;
  while($hash{$dep}[$i]){
    if(!(inlist(0, $hash{$dep}[$i]))){
      $_ = $hash{$dep}[$i];
      #s/\.aix\d\.\d.*//;
      s/-\d$//;
      $ret = $ret . $url . $location{$_} . "/" . $hash{$dep}[$i] . "*\n";
      my $tmp = $hash{$dep}[$i];
      if($hash{$tmp}[0]){
        push @iarray, $i;
        $ret = $ret . installdependency($url, $dep, $hash{$dep}[$i], \@curip, %hash);
        $i = pop(@iarray);
      }
    }
    $i++;
  }
  return($ret);       
}  ## end installdependency



#################################################
#	GETDEPENDENCIES				#
# Gets dependencies from $dependencyfile and	#
# stores only those Rpm's needed by the 	#
# client in hash->arrays. 			#
# Calls uiupdate()				#
#################################################
sub getdependencies{

  my ($url, $dep, @diff) = @_;
  my ($mynode, $diff, $key, $a, $i, @nodes, %dephash);

  undef %GLOBALhash;
  initializeglobalhash(@diff);

  open(INDEP, $dep);
  while(<INDEP>){

    ### Get and format list of nodes(first is key)
    s/^\>\s+//g;
    s/plus/\+/g;
    @nodes = split /:/, $_;
    
    ### Get and format Head node (key) 
    $a = shift(@nodes);
    chomp($a);
    $a =~ s/\s*//g;

    ### Insert nodes into hash at key $a
    $i = 0;
    foreach $mynode (@nodes){
      $mynode =~ s/\s*//g;

      if($a){
        ### Only add dependency lists that the client is missing
        if(inlist(0, $a)){
          $dephash{$a}[$i++] = $mynode;
        }
      }
    }
  }
  close(INDEP);

  ### Hack to get around wu-ftpd/proftpd conflict
  ### (Can't install both).  If proftpd is installed then ignore wu-ftpd,
  ### and vice-versa.
  my @tmparray = (keys %dephash);
  my ($wu, $pro); 
  foreach(@tmparray){
    $wu = $1 if(/(wu-ftpd.*)/);
    $pro = $1 if(/(proftpd.*)/);
  } 
  my $isproftpdinstalled = `rpm -q proftpd 2> /dev/null`;
  if( (($wu) && (!($pro))) || (($wu) && ($isproftpdinstalled))  ){
    delete $dephash{$wu}; 
  }
  else{ delete $dephash{$pro}; }

  ##  printhashtable(%dephash);
 
  uiupdate($url, %dephash);

}  ## end getdependencies



#################################################
#	INLIST					#
# Checks to see if $file is inside @list	#
# 1 type means check exact package name.	#
# 0 type means only check textual part of name	#
#  Used so we only update packages, not install	#
#  new ones. 					#
#################################################
sub inlist{
  my ($type, $file) = @_;

  if($file){
    chomp($file);
    $file =~ s/ssl//g;
    $_ = $file;
    /^(\w[\w|\d|\+])/;
    my $listptr = $GLOBALhash{$1};
    my @list;
    if($listptr){
      for(my $i=0; $i<@$listptr; $i++){
        $list[$i] = $listptr->[$i];  #get at a particular index within array
      }
  
      if($type == 1){
        $file =~ s/\-\d.*//;
      }
      else{
        $file =~ s/\.aix\d\.\d.*//g;
      }
  
      foreach my $item (@list){
        chomp($item);
        $item =~ s/ssl//g;
        my $leret = $item;
        $item =~ s/\.aix\d\.\d.*//;
        if($type == 1){
          $item =~ s/\-\d.*//;
        }
        if($file eq $item){
          return($leret);
        }
      }
      return(0);
    }
    else{
      return(0);
    }
  }
  else{
    return(0);
  }
}
sub initializeglobalhash{
  my @array = @_;
  my $i = 0;
  my $prevletter = "first";
  my $currletter = "";
  my @tmparray = "";

  foreach (sort @array){
    chomp($_);
    s/^\s*//;
    /^(\w[\w|\d|\+])/;
    $currletter = $1;

    if(($prevletter eq $currletter) || ($prevletter eq "first")){
      if($prevletter eq "first"){
        @tmparray = $_;
      }
      else{
        push @tmparray, $_;
      }
      $prevletter = $currletter;
    }
    else{
      $GLOBALhash{$prevletter} = [ @tmparray ];
      @tmparray = $_;
      $prevletter = $currletter;
    }
  }
  $GLOBALhash{$currletter} = [ @tmparray ];
}


 
#################################
#	PRINTHASHTABLE		#
# Prints all elements in	#
# the hashtable.  		#
# Assumes format:		#
# $hash{$key}[$array_index]	#
#################################
sub printhashtable{
  my (%hash) = @_;
  my ($key, $i);
  print "Printing whole list:\n";
  foreach $key (sort keys %hash){
    $i = 0;
    print "Head is $key\n";
    while($hash{$key}[$i]){
      print "  Hash{$key}[$i] is " . $hash{$key}[$i++] . "\n";
    }
  }

} ## end printhashtable



#########################################
#	GETDIFF				#
# Gets .rpm files missing from the	#
# client's computer.  Outputs 		#
# differences into $diff_file		#
#########################################
sub getdiff{
  my ($loc, $ser, $diff_file) = @_;
  my @diff = `diff $ser $loc`;
  my @tmp;
  my $i = 0;

  `touch $diff_file`;
  `rm $diff_file`;

  open(OUT, ">$diff_file");
  foreach (@diff){
    if($_ =~ /^\</){
      s/plus/\+/g;
      s/\<//g;
      s/^\s//g;
      print OUT $_;
      $tmp[$i++] = $_;
    }
  }
  close(OUT);
  
  return(@tmp); 

}  ## end getdiff



#########################################
#	GETLOCALLIST			#
# Gets list of locally installed .rpms	#
# Prints to file $localfile and returns	#
# the list in an array.			#
#########################################
sub getlocallist{
  my ($localfile) = @_;
  my $i;

  ### Get the list of available rpms from the client
  ### Store them in file "$$.locallist"
  my @locallist = `rpm -qa --queryformat "%{NAME}-%{VERSION}-%{RELEASE}.%{OS}.%{ARCH}.rpm-%{EPOCH}\n"`;
  @locallist = sort @locallist;

  `touch $localfile`;
  `rm $localfile`;

  open(OUT, ">$localfile");
  
  foreach $i (@locallist){
    $_ = $i;
    s/-\(none\)/-1/;
    s/plus/\+/g;
    s/ssl//g;
    print OUT $_;
  }
 
  close(OUT);

}  ## end getlocallist



#########################################
#	GETSERVERLIST			#
# Gets list of .rpms installed on server#
# Prints to file $serverfile and returns#
# the list in an array.			#
#########################################
sub getserverlist{
  my ($serverfile, $importfile) = @_;
  my $i = 0;

  ### Get the list of available rpms from the server
  ### and their corresponding locations
  ### Store it locally as "$$.serverlist"

  `touch $serverfile`;
  `rm $serverfile`;
 
  open(SESAME, $importfile);
  open(OUT, ">$serverfile");
  while (<SESAME>){
    s/plus/\+/g;
    my $line = $_;
    if( (($oslevel =~ /4\.3/) && ($line =~ /.*aix$oslevel/)) || ($oslevel =~ /^5.*/)){
      $line =~ s/(.*)\/(.*\.aix\d\.\d.*)/$2/;
      $location{$2} = $1;
      unless (($line =~ /^-/) || ($line =~ /^AIX/) || ($line =~ /^\n/)){
        print OUT $line;
      }
    }
  }
  close(OUT);
  close(SESAME);

  `sort $serverfile > $$.txt`;
  `cp $$.txt $serverfile`;
  `rm $$.txt`;

}  ## end getserverlist



#################################
#	CLEANARRAY		#
# Cleans array. Removes		#
# newlines and AIX.* which	#
# pops up numerous times	#
#################################
sub cleanarray{
  my (@a) = @_;
  my @b;
  my $item;
  my $i = 0;

  foreach $item (@a){
    unless (($item =~ /^-/) || ($item =~ /^AIX/)){
      $b[$i++] = $item;
    }
  }
 
  return(@b);

}  ## end cleanarray



#################################
#	SETARGUMENTLIST		#
# Sets global variables 	#
# according to specified	#
# commandline arguments		#
# Only supports 4 consecutive	#
# arguments, (-hadq).  		#
# Three is all we ever need.	#
#################################
sub setargumentlist{
  my (@parameters) = @_;

  foreach my $param (@parameters){
    $param =~ s/\,//g;
    if($param =~ /^\-\w+/){
      $param =~ s/^(\-\w)(\w)(\w)(\w)(\w)/$1 \-$2 \-$3 \-$4 \-$5/g;
      $param =~ s/^(\-\w)(\w)(\w)(\w)/$1 \-$2 \-$3 \-$4/g;
      $param =~ s/^(\-\w)(\w)(\w)/$1 \-$2 \-$3/g;
      $param =~ s/^(\-\w)(\w)/$1 \-$2/g;
    }
    if(($param =~ /\-s/) || ($param =~ /^\-\-save/)){
      $save = 1;
    }
    if(($param =~ /\-q/) || ($param =~ /^\-\-quer/)){
      $query = 1;
    }
    if(($param =~ /\-a/) || ($param =~ /^\-\-all/)){
      $all = 1;
    }
    if(($param =~ /\-l/) || ($param =~ /^\-\-lang/)){
      $lang = 1;
    }
    if(($param =~ /\-i/) || ($param =~ /^\-\-iter/)){
      $iterative = 1;
    }
    if(($param =~ /\-o/) || ($param =~ /^\-\-outp/)){
      $output = 1;
    }
    if( ($param =~ /^\w/) ){
      $logname = $param;
    }
    if(($param =~ /\-d/) || ($param =~ /^\-\-down/)){
      $save = 1;
      $down = 1;
    }
    if(($param =~ /[A-Z]/) || ($param =~ /^\-\-help/) || ($param =~ /\-[b-c|e-h|j-k|m-n|p|r|t-z]/) || ($param =~ /^\-\-[b-c|e-h|j-k|m-n|p|r|t-z]/) || (($param =~ /\-\W/) && ($param !~ /\-\-/)) || ($param =~ /\-\-\W/) ){
      ### Help Statement (-h)
      my $usage = <<EOF;

Usage: update_tbox -[adqsil]
options:
  -a, --all             install ALL available packages in the Toolbox
                          (can take a long time an requires LOTS of disk space)
  -d, --download        only download rpms; don't install
  -q, --query           print what's out of date; don't download or install
  -s, --save            don't delete rpms after installing
  -i, --iterative       download, install, remove each file one at a time, not all at once
                          (may not install files with concurrent dependencies)
  -l, --lang            prompt to install language-specific packages
  -o logfile, --output  save all output in logfile(default [pid].logfile)
  -h, --help            print this statement
  No Flag               only updates previously installed out-of-date packages
                          (and dependencies, if applicable)
EOF

      print $usage;
      exit;
    }
  }
}  ## end setargumentlist



#################################
# 	CLEANUP 		#
# Removes all temporary files 	#
# used by script.		#
#################################
sub cleanup{
  `rm $$.urllist $localname $servername $diffname $importfile $dependencyfile >/dev/null 2>&1`;
} ## end cleanup



#########################################
# 	PUSHTOHASH			#
# Pushes the newly found rpm to 	#
# the list of rpms already installed	#
# or waiting to be installed		#
#########################################
sub pushtohash{
  my ($key) = @_;
  my (@list, $i, $listptr);

  $_ = $key;
  /(\w[\w|\d|\+])/;
  $listptr = $GLOBALhash{$1};
  if($listptr){
    for($i=0; $i<@$listptr; $i++){
      $list[$i] = $listptr->[$i];  #get at a particular index within array
    }
    push @list, $key;
    $GLOBALhash{$1} = [ @list ];
  }
  else{
    @list = $key;
    $GLOBALhash{$1} = [ @list ];
  }

}
