#!/usr/bin/perl
#
# Write to output lines suitable for feeding to
#
# dpkg --set-selections
#
# that reflect current installation status.  This
# script uses /var/lib/dpkg/status to obtain current
# installation status.
#
# This array maps current status to desired status.
# Strings lifted from /usr/doc/dpkg/internals.html/internals.html
%selstatus = ('not-installed', 'purge',
              'unpacked', 'install',
              'half-configured', 'install',
              'installed', 'install',
              'half-installed', 'install',
              'config-files', 'deinstall',
              'postinst-failed', 'install',
              'removal-failed', 'deinstall');

open (STATUS, '/var/lib/dpkg/status') || die 'Cant read /var/lib/dpkg/status';

$package = '';
$status = '';
$line = 0;

while (<STATUS>) {
  chomp;
  $line++;;
  SWITCH: {
    if (/^Package:\s+(\S+)/i) { 
      if ($package) {
        print "** Aargh!  Package $package has no status recorded at line $line\n";
        die "Aargh!  Package $package has no status recorded at line $line\n";
      }
      $package = $1;
      
      last SWITCH;
    } elsif (/^Status:\s+\S+\s+\S+\s+(\S+)/i) {
      if ($status) {
        print "** Aargh!  Package $package has more than one status at line $line\n";
        die "Aargh!  Package $package has more than one status at line $line\n";
      }
      unless ($package) {
        print "** Aargh!  No package for status at line $line\n";
        die "Aargh!  No package for status at line $line\n";
      }
      $status = $1;
      if (exists $selstatus{$status}) {
        print "$package " . $selstatus{$status} . "\n";
      } else {
        print "** Aargh!  Unknown package status $status at line $line\n";
        die "Aargh!  Unknown package status $status at line $line\n";
      }
      $package = '';
      $status = '';
    }
  }
}
close STATUS;

if ($package) {
  print "** Aargh!  Final package $package has no status; truncated input?\n";
  die "Aargh!  Final package $package has no status; truncated input?\n";
}
