#!/usr/bin/perl

use 5.010001;
use strict;
use warnings;
use Log::Any '$log';

BEGIN { $ENV{LOG} //= 0 } # speedup startup

use Getopt::Long;

our $VERSION = '1.35'; # VERSION

my %opts = (
    library => [],
    subcommands => [],
    version => 0,
);
Getopt::Long::Configure('pass_through', 'no_permute');
GetOptions(
    'library|I=s' =>  $opts{library},
    'help|h|?'    => \$opts{help},
    'version|v'   => \$opts{version},
    'list|l'      => \$opts{list},
);

my $me = $0; $me =~ s!.+/!!;

if ($opts{version}) {
    print "$me version $main::VERSION\n";
    exit 0;
} elsif ($opts{list}) {
    require Module::List;
    my $mm = Module::List::list_modules("Data::Unixish::",
                                        {list_modules=>1, recurse=>1});
    for (sort keys %$mm) {
        next unless /^Data::Unixish::([a-z].*)/;
        say $1;
    }
    exit 0;
} elsif ($opts{help} || !@ARGV) {
    print <<USAGE;
$me - Run dux function on the command-line

Usage:
  $me --help
  $me [common options] <dux function> [function options]

*Common options* include: '--library' ('-I') to add directory to Perl search dir
(a la Perl's '-I'), can be specified multiple times.

Examples:
  Show usage for a dux function:
    % $me head --help

  Run dux function:
    % ls -l | $me head -n 3

USAGE
    exit 0;
}

for my $dir (@{ $opts{library} }) { require lib; lib->import($dir) }

require Perinci::CmdLine::dux;
my $cmd = Perinci::CmdLine::dux->new;

my $pkg = shift @ARGV;
require Module::Path;
die "Unknown dux function $pkg, ".
    "please see list of available functions using `$me -l`\n" unless
    Module::Path::module_path("Data::Unixish::$pkg");

$pkg =~ s!::!/!g;
my $func = $pkg; $func =~ s!.+/!!;
my $url  = "/Data/Unixish/$pkg/$func";
$cmd->url($url);
$cmd->program_name($func);
$cmd->run;

#ABSTRACT: Run dux function on the command-line
#PODNAME: dux

__END__

=pod

=head1 NAME

dux - Run dux function on the command-line

=head1 VERSION

version 1.35

=head1 SYNOPSIS

Type C<dux --help> for more help.

=head1 DESCRIPTION

By default this script sets LOG environment to 0. If you want to enable logging,
you have to specifically set LOG=1.

=head1 SEE ALSO

L<Data::Unixish>

=head1 AUTHOR

Steven Haryanto <stevenharyanto@gmail.com>

=head1 COPYRIGHT AND LICENSE

This software is copyright (c) 2013 by Steven Haryanto.

This is free software; you can redistribute it and/or modify it under
the same terms as the Perl 5 programming language system itself.

=cut
