#!/usr/bin/perl

=head1 NAME

whichpm - locate a Perl module and it's version

=head1 SYNOPSIS

	# shows path and version (if vailable) of the Perl module
	whichpm Some::Module::Name
	whichpm -v Some::Module::Name
	whichpm --verbose Some::Module::Name

	# shows just path to the Perl module
	whichpm -q Some::Module::Name
	whichpm --quiet Some::Module::Name

	# add lib/ into @INC
	whichpmv -l Some::Module::Name
	# add mylib into @INC
	whichpmv -Imylib Some::Module::Name

	# show version of App::whichpm
	whichpm --version

	# show/edit .pm file
	less `whichpm Some::Module::Name`
	vim `whichpm Some::Module::Name`

=head1 DESCRIPTION

Loads the module, prints its file system location and version.

When STDOUT is not a TTY, prints just file name by default. (-v can force
printing version too)

=cut


use strict;
use warnings;

use App::whichpm qw(which_pm);
use Getopt::Long qw(:config no_ignore_case);
use Pod::Usage;

exit main();

sub main {
	my $help;
	my $quiet = (-t STDOUT ? 0 : 1);
	my ($version, $verbose, @into_inc, $add_lib);

	# allow -Ilib style of include dir options
	@ARGV = map { $_ =~ m/^-I(.+)$/ ? ('-I', $1) : $_ } @ARGV;

	GetOptions(
		'help|h'    => \$help,
		'quiet|q'   => \$quiet,
		'version|V' => \$version,
		'verbose|v' => \$verbose,
		'I=s'       => \@into_inc,
		'lib|l'     => \$add_lib,
	) or pod2usage;
	pod2usage if $help;

	unshift(@INC, @into_inc);
	unshift(@INC, 'lib')
		if $add_lib;

	$quiet = 0 if $verbose;

	# show version
	if ($version) {
		print App::whichpm->VERSION, "\n";
		return 0;
	}

	unless (@ARGV) {
		print STDERR "usage: $0 Some::Module::Name\n";
		return 1;
	}

	# lookup for all modules passed on command line
	my $all_ok = 1;
	while (my $mn = shift @ARGV) {
		my ($filename, $version) = which_pm($mn);

		# don't show version in quiet mode
		$version = undef
			if $quiet;

		if ($filename) {
			print $filename, (defined $version ? ' '.$version : ()), "\n";
		}
		else {
			$all_ok = 0;
		}
	}

	return ($all_ok ? 0 : 1);
}
