#!/usr/bin/perl

=pod

=head1 NAME
 
B<apt-echo> - echos valid package names

=head1 SYNOPSIS

B<apt-echo> [I<-h>]

B<apt-echo> [I<-v>]

B<apt-echo> [I<-s>] I<pkg1> [I<pkg2...>]

=head1 DESCRIPTION

B<apt-echo> is a tool to verify package names.

B<apt-echo> takes package names, and looks them up in the apt cache. If the package
exists, the name is returned to the user. Otherwise, there is no output.

=head1 OPTIONS

=over

=item B<-h, --help>

Prints help text

=item B<-v, --version>

Prints the B<apt-echo> version 

=item B<-s, --source>

Looks up source package names instead of binary package names

=back

=head1 RETURN CODES

Returns the number of incorrect packages.

Returns 0 if all arguments are valid packages.

Returns -1 on any other error.

=head1 BUGS

None, hopefully.

=head1 SEE ALSO

I<apt-cache>(8), I<aptitude>(8)

=head1 AUTHOR

Copyright 2010 William Orr <will@worrbase.com>

This is free software, see the GNU General Public License version 2 or later for
copying conditions. There is NO warranty.
=cut


use strict;
use warnings;

use AptPkg::Cache;
use AptPkg::Source;
use Getopt::Long;

our $VERSION = '0.10';

my ($source, $help, $version) = '';
my $incorrect = 0;

GetOptions('source|s'  => \$source, 
           'help|h'    => \$help, 
           'version|v' => \$version);

sub get_binary {
    my $pkg_name = shift;
    my $apt_cache = AptPkg::Cache->new;
    if (exists $apt_cache->{"$pkg_name"}) {
        return 1;
    } else {
        return 0;
    }
}

sub get_source {
    my $src_name = shift;
    my $source_cache = AptPkg::Source->new;
    if ($source_cache->find("$src_name", 1)) {
        return 1;
    } else {
        return 0;
    }
}

sub help_text {
    print <<EOF
Usage: apt-echo [-h|--help]
       apt-echo [-v|--version]
       apt-echo [-s|--source] pkg_name

Echos any valid packages supplied as arguments to user

Options:
    -h|--help       - prints this help text
    -v|--version    - prints apt-echo's version
    -s|--source     - apt-echo for source packages
EOF
}

sub version_text {
    print "apt-echo version $VERSION\n";
}

if ($help or @ARGV == 0 and not $version) {
    help_text;
    exit 0;
}

if ($version) {
    version_text;
    exit 0;
}

if ($source) {
    foreach (@ARGV) {
        if (get_source($_)) {
            print "$_ ";
        } else {
            $incorrect += 1;
        }
    }
} else {
    foreach (@ARGV) {
        if (get_binary($_)) {
            print "$_ ";
        } else {
            $incorrect += 1;
        }
    }
}

if (@ARGV != $incorrect) {
    print "\n";
}

exit $incorrect;
