#! /usr/bin/perl
use warnings;
use strict;
use integer;
use FindBin;
use lib $FindBin::RealBin;
use Def;
$/ = '';

# This script checks that you have all the standard- and higher-priority
# packages listed in the Packages file fully installed on your system,
# and that you have the right versions installed.  Any you do not have
# properly installed, it prints the names of to stdout, one per line.

our $usage = <<END;
usage: $0 [-1qh] [Packages-file]
    -1 exit nonzero if any packages are missing
    -q quiet: do not print the names of missing packages to stdout
           (note: the -q opt does not suppress error messages on stderr)
    -h print this help message
END

my $any_missing = '';

my %opt;
for my $i ( reverse 0 .. $#ARGV ) {
  my( $o ) = $ARGV[$i] =~ /^-(.+)/;
  next unless defined $o;
  splice @ARGV, $i, 1;
  $opt{ substr $o, $_, 1 } = 1 for 0 .. length($o)-1;
}
$opt{h} || $opt{'?'} and print( $usage ), exit;

while (<>) {
  my( $pkg ) = /^${Def::Package}: (\S+)\s*$/m
    or warn "$0: can find no Package field in\n$_";
  my( $pri ) = /^${Def::Priority}: (\S+)\s*$/m
    or warn "$0: can find no Priority field in\n$_";
  my( $ver ) = /^${Def::Version}: (\S+)\s*$/m
    or warn "$0: can find no Version field in\n$_";
  next if $pri eq 'optional' || $pri eq 'extra';
  my $dpkg_s = `dpkg -s $pkg 2>/dev/null`;
  my $dpkg_err = $?;
  my( $instver ) = $dpkg_s =~ /^Version: (\S+)\s*$/m;
  next if !$dpkg_err &&
    $dpkg_s =~ /^Status: install ok installed$/m &&
    defined($instver) && $instver eq $ver;
  print "$pkg\n" unless $opt{q};
  $any_missing = '1';
}

exit 1 if $opt{1} && $any_missing;

