#!/usr/bin/perl -w
# Copyright (c)2001-2002 Joe Wreschnig
# Feta plugin for installing recommended packages.
# Licensed under the GNU GPL.

use Getopt::Std;
use strict;

my %opts; getopts('tyqV', \%opts);

my @toinstall;

if (@ARGV == 0) {
 print STDERR "E: You must provide at least one package name.\n";
 exit 1;
}

foreach my $package (@ARGV) {
 my @info = `apt-cache depends $package`;
 while (my $p = shift @info) {
  my @possible;
  if ($p =~ /Recommends: (.*)/) {
   $possible[0] = $1;
   my $or = 0;
   if ($p =~ /\|/) { $or = 1; }
   while ($info[0] && ($info[0] !~ /:/ || $or)) {
    $or = 0;
    if ($info[0] =~ /\|/) { $or = 1; }
    $info[0] =~ s/\s+(.*: )?(.+)/$2/g;
    chomp($info[0]);
    push(@possible, shift @info);
   }

   if (@possible == 1 || $opts{'y'}) { push(@toinstall,  $possible[0]); }

   else {
    @possible = sort_uniq(@possible);
    my $i;
    for ( $i = 0; $possible[$i]; $i++) {
     if ($possible[$i] =~ /^<.*>$/) {
      splice (@possible, $i, 1);
      $i--;
     } else { print "$i)  $possible[$i]\n"; }
    }
    print "$i)  None of the above.\n\n";

    print "Please choose one to install [0-$i]: ";
    chomp (my $num = <STDIN>);
    if ($num != $i) { push(@toinstall, $possible[$num]); }
   }
  }
 }
}

if (@toinstall == 0) {
 print STDERR "W: There are no packages to install.\n";
 exit 0;
}

sub sort_uniq { my %a; @a{@_} = 1; return sort keys %a; } # Inefficient. Short.

if (!$opts{'q'}) {
 print "Installing " . join(", ", @toinstall) . ".\n\n";
 print "Some of these packages may already be installed. If they are, they will not\n";
 print "be reinstalled, but they will be upgraded if possible.\n\n";
}

exit system("feta", feta_opts(), "install", @toinstall);

sub feta_opts {
 my @opts;
 foreach ('y','t','V','q') { if ($opts{$_}) { push (@opts, "-$_"); } }
 return @opts;
}
