#!/usr/bin/env perl
## no critic (ControlStructures::ProhibitPostfixControls)
## no critic (ValuesAndExpressions::ProhibitConstantPragma)
use strict;
use warnings;
use feature qw( say );
use open ':std', IO => ':encoding(UTF-8)';

# ABSTRACT: Ensure that the environment variables match what you need, or abort.

# PODNAME: envassert

our $VERSION = '0.004'; # VERSION: generated by DZP::OurPkgVersion

use English qw( -no_match_vars );    # Avoids regex performance penalty in perl 5.18 and earlier
use Getopt::Long;
use Carp;
use Pod::Usage;

use Env::Assert qw( :all );

local $OUTPUT_AUTOFLUSH = 1;

use constant {
    YEAR_START        => 1900,
    MONTH_START       => 1,
    ENV_DESC_FILENAME => '.envdesc',
    INDENT            => q{    },
};

my $help = 0;
my $man  = 0;
my $break_at_first_error;
my $env_desc_filename = ENV_DESC_FILENAME;
GetOptions(
    'help|?'                  => \$help,
    'man'                     => \$man,
    'break-at-first-error|b!' => \$break_at_first_error,
    'env-description|e=s'     =>,
    \$env_desc_filename,
) or pod2usage(2);
pod2usage(1)                              if $help;
pod2usage( -exitval => 0, -verbose => 2 ) if $man;

sub main {

    open my $fh, q{<}, $env_desc_filename or croak "Cannot open file '$env_desc_filename'";
    my $env_desc_file = q{};
    my @env_desc_rows;
    while (<$fh>) { chomp; push @env_desc_rows, $_; }
    close $fh or croak "Cannot close file '$env_desc_filename'";

    my $desc = file_to_desc(@env_desc_rows);
    my %parameters;
    $parameters{'break_at_first_error'} = $break_at_first_error
      if defined $break_at_first_error;
    my $r = assert( \%ENV, $desc, \%parameters );
    if ( !$r->{'success'} ) {
        ## no critic (InputOutput::RequireCheckedSyscalls)
        say report_errors( $r->{'errors'} );
        return 1;
    }
    return 0;
}

exit main(@ARGV);

__END__

=pod

=encoding UTF-8

=head1 NAME

envassert - Ensure that the environment variables match what you need, or abort.

=head1 VERSION

version 0.004

=head1 SYNOPSIS

envassert [options]

Options:
    --help
    --man
    --break-at-error
    --env-description

=head2 CLI interface without dependencies

The F<envassert> command is also available
as self contained executable.
You can download it and run it as it is without
additional installation of CPAN packages.
Of course, you still need Perl, but Perl comes with any
normal Linux installation.

This can be convenient if you want to, for instance,
include F<envassert> in a docker container build.

    curl -LSs -o envassert https://raw.githubusercontent.com/mikkoi/env-assert/master/script/envassert.packed
    chmod +x ./envassert

=head1 DESCRIPTION

B<envassert> checks that your runtime environment, as defined
with environment variables, matches with what you want.

You can define your required environment in a file.
Default file is F<.envassert> but you can use any file.
It is advantageous to use B<envassert> for examnple when running
a container. If you check your environment for missing or
wrongly defined environment variables at the beginning of
the container run, your container will fail sooner instead
of in a later point in execution when the variables are needed.

=head2 Environment Description Language

Environment is described in file F<.envdesc>.
Environment description file is a Unix shell compatible file,
similar to a F<.env> file.

=head3 F<.envdesc> Format

In F<.envdesc> file there is only environment variables, comments
or empty rows.
Example:

    # Required env
    ## envassert (opts: exact=1)
    FILENAME=^[[:word:]]{1,}$'

Env var name is followed by a regular expression. The regexp is
an extended Perl regular expression without quotation marks.
One env var and its descriptive regexp use one row.

A comment begins at the beginning of the row and uses the whole row.
It start with '#' character.

Two comment characters and the word B<envassert> at the beginning of the row
mean this is an B<envassert> meta command.
You can specify different environment related options with these commands.

Supported options:

=over 8

=item exact

The option I<exact> means that all allowed env variables
are described in this file. Any unknown env var causes an error
when verifying.

=back

=head1 envassert

Ensure that the environment variables match
what is requested, or abort.

=head1 OPTIONS

=over 8

=item B<--help>

Print a brief help message and exits.

=item B<--man>

Prints the manual page and exits.

=item B<-b>, B<--break-at-first-error>

Break checking at the first error and report back.
Default: false

=item B<-e>, B<--env-description>

Path to file which has the environment description.
Default: .envdesc

=back

=head1 DEPENDENCIES

No external dependencies outside Perl's standard distribution.

=head1 AUTHOR

'Mikko Koivunalho <mikkoi@cpan.org>'

=head1 COPYRIGHT AND LICENSE

This software is copyright (c) 2023 by Mikko Koivunalho.

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
