#!/usr/bin/perl -w
#
# Copyright 2000 Steve McIntyre <stevem@chiark.greenend.org.uk>
# See the README file for the license
#
# This script takes 2 arguments on input - the filename of a packages list and
# the output filename
#
# The job of this script is to remove all non-US packages from that packages 
# list.

use strict;

my $infile = shift;
my $outfile = shift;

my $apt = "$ENV{'BASEDIR'}/tools/apt-selection";
my $adir = "$ENV{'APTTMP'}/$ENV{'CODENAME'}-$ENV{'ARCH'}";
my $dir = "$ENV{'TDIR'}/$ENV{'CODENAME'}-$ENV{'ARCH'}";
my $verbose = $ENV{'VERBOSE'} || 0;
my $nonuslist = "$dir/non-US.list";

$| = 1; # Autoflush for debugging

open(LOG, ">>$dir/log.strip-nonUS-bin") 
    || die "Can't write in $dir/log.strip-nonUS-bin !\n";

sub msg {
	my $level = shift;
	if ($verbose >= $level) {
		print @_;
	}
	print LOG @_;
}

msg(2, "$infile\n");

my %packages;

# Get the informations on all packages
my $oldrs = $/;
$/ = '';
open(AVAIL, "$apt cache dumpavail |") || die "Can't fork : $!\n";
my ($p, $re);
while (defined($_=<AVAIL>)) {
    next if not m/^Package: (\S+)\s*$/m;
    $p = $1;
    if( m/^(Section|Filename): \S*non-US\S*\s*$/m )
    {
        $packages{$p}{"nonus"} = 1;
    } else {
        $packages{$p}{"nonus"} = 0;
    }
}
close AVAIL or die "apt-cache failed : $@ ($!)\n";
$/ = $oldrs;

# Now for each package in the specified package list, check it against
# our database. If it's non-US lose it.
open (INLIST, "< $infile") 
    || die "Can't open starting list $infile\n";
open (OUTLIST, "> $outfile") 
    || die "Can't open starting list $outfile\n";

while(defined($_=<INLIST>)) {
    chomp;
    if($packages{$_}{"nonus"}) {
        msg(2, "Removing non-US package $_\n");
    } else {
        msg(2, "Keeping package $_\n");
        print OUTLIST "$_\n";
    }
}
close INLIST;
close OUTLIST;
close LOG;
