#!perl

our $DATE = '2015-09-10'; # DATE
our $VERSION = '0.04'; # VERSION

use 5.010001;
use strict;
use warnings;

use Getopt::Long::EvenLess;

sub _help {
        print <<'_';
Usage:
  errno <num>
  errno <search string>
  errno --list (-l)
  errno --help (-h, -?)
  errno --version (-v)
_
}

my @errnos;
{
    my $i = 0;
    local $!;
    while (1) {
        $i++;
        $! = $i;
        my $str = "$!";
        last if $str =~ /unknown error/i;
        push @errnos, [$i, $str];
        last if $i >= 255; # hard limit, should anything goes wrong
    }
}

GetOptions(
    'help|h|?' => sub {
        _help();
        exit 0;
    },
    'version|v' => sub {
        no warnings 'once';
        say "errno version $main::VERSION";
        exit 0;
    },
    'list|l' => sub {
        for (@errnos) { say "$_->[0]\t$_->[1]" }
        exit 0;
    },
);

if (@ARGV != 1) {
    _help();
    exit 1;
}

if ($ARGV[0] =~ /\A\d+\z/) {
    local $! = +$ARGV[0];
    my $str = "$!";
    say $str;
    exit $str =~ /unknown error/i ? 1:0;
} else {
    my $search = lc($ARGV[0]);
    my $found;
    for (@errnos) {
        if (index(lc($_->[1]), $search) >= 0) {
            say "$_->[0]\t$_->[1]";
            $found++;
        }
    }
    exit $found ? 0 : 1;
}

# ABSTRACT: List/show errno
# PODNAME: errno

__END__

=pod

=encoding UTF-8

=head1 NAME

errno - List/show errno

=head1 VERSION

This document describes version 0.04 of errno (from Perl distribution App-errno), released on 2015-09-10.

=head1 SYNOPSIS

Show the error message string for a certain errno code:

 % errno 23

Search error message string:

 % errno file

List all known errno's on your system:

 % errno -l

=head1 DESCRIPTION

This script can be used to show the error message of a particular C<errno>, or
list all available errno's on your system.

=head1 HOMEPAGE

Please visit the project's homepage at L<https://metacpan.org/release/App-errno>.

=head1 SOURCE

Source repository is at L<https://github.com/perlancar/perl-App-errnos>.

=head1 BUGS

Please report any bugs or feature requests on the bugtracker website L<https://rt.cpan.org/Public/Dist/Display.html?Name=App-errno>

When submitting a bug or request, please include a test-file or a
patch to an existing test-file that illustrates the bug or desired
feature.

=head1 AUTHOR

perlancar <perlancar@cpan.org>

=head1 COPYRIGHT AND LICENSE

This software is copyright (c) 2015 by perlancar@cpan.org.

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
