#!/usr/bin/perl -w
#
use strict;
use English;
#
if ( $#ARGV > 1 or $#ARGV < 0 )
  {
  print "Usage: UpGrade [ path to packages ] list_file \n";
  exit 1;
  }
my($packagepath, $searchpath, $filename, $record, $archtype, $rname, $dname);
my($version, $package, $available, $status, $check1, $check2, $command, $i);
my(@hold);
if ( $#ARGV < 1 )
  {
  $packagepath=`pwd`;
  chomp $packagepath;
  $filename=$ARGV[0];
  }
else
  {
  $packagepath=$ARGV[0];
  $filename=$ARGV[1];
  }
$archtype=`dpkg --print-architecture`;
chomp $archtype;
#
open (INPUTFILE, "<$filename")  or die "Can't open $filename\n";
#
while ($record = <INPUTFILE>)
  {
  chomp $record;
  my(@lst)=split(/ /, $record);
  if ("$lst[0]" ne "#") 
    {
    if ("$lst[0]" eq "-i")
      {
      $rname=$lst[$#lst];
      $searchpath=join('',$packagepath,$lst[$#lst - 1]);
      if ("$rname" eq "ld.so")
        {
        $dname="ldso";
        }
      elsif ("$rname" eq "sysklogd")
        {
        $dname="syslogd";
        }
      elsif ("$rname" eq "sh-utils")
        {
        $dname="shellutils";
        }
      else
        {
        $dname=$rname;
        }
      $command="dpkg -s $dname |gawk '/Version:/ { print" . '$2' . "}'";
      $version=`$command`;
      chomp $version;
system ("echo '$rname'");
      @hold=`ls $searchpath$rname*.deb |grep -w $rname`;
      $available=$hold[0];
      chomp $available;
      $command="dpkg -s $dname |gawk '/Status:/ { print" . '$NF' . "}'";
      $status=`$command`;
      chomp $status;
      $check1=join('',$searchpath,$rname,"-",$version,".",$archtype,".deb");
      $check2=join('',$searchpath,$rname,"-",$version,".deb");
      if( ($check1 eq $available) or ($check2 eq $available) and ("$status" eq "installed") ) 
        {
        $package="$rname" . "-" . "$version";
        system ("echo 'Package $package is already installed.'");
        }
      else
        {
        $command="dpkg ";
        for ($i = 0; $i < $#lst - 1; $i++) { $command=$command . $lst[$i] . " "; }
        $command=$command . $available;
        system("echo '$command'");
        system($command);
        }
      }
    elsif ( "$lst[0]" eq "--purge" )
      {
      $command="dpkg -s $lst[$#lst] |gawk '/Status:/ {print " . '$NF' . "}'";
      $status=`$command`;
      chomp $status;
      if ("$status" eq "not-installed")
        {
        system ("echo 'Cannot purge $lst[$#lst]. It is not installed.'");
        }
      else
        {
        $command="dpkg ";
        for ($i = 0; $i < $#lst+1; $i++) {$command=$command . $lst[$i] . " ";}
        system("echo '$command'");
        system($command);
        }
      }
    else
      {
      $command="dpkg ";
      for ($i = 0; $i < $#lst + 1; $i++) { $command=$command . $lst[$i] . " "; }
      system("echo '$command'");
      system($command);
      }
    }
  }
close INPUTFILE;
system ("echo '$0 from file: $filename is complete.'");
exit 0;