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

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

# PODNAME: envassert

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

use English      qw( -no_match_vars );                   # Avoids regex performance penalty in perl 5.18 and earlier
use Getopt::Long qw( :config auto_version auto_help );
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 $man = 0;
my $break_at_first_error;
my $env_desc_filename = ENV_DESC_FILENAME;
my $exact;
GetOptions(
    'man'                     => \$man,
    'break-at-first-error|b!' => \$break_at_first_error,
    'env-description|e=s'     =>,
    \$env_desc_filename,
    'exact|x!' => \$exact,
) or pod2usage(2);
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;
    $desc->{'options'}->{'exact'} = $exact
      if defined $exact;
    my $r = assert( \%ENV, $desc, \%parameters );
    if ( !$r->{'success'} ) {
        print {*STDOUT} report_errors( $r->{'errors'} )
          or croak 'Cannot print errors to STDOUT';
        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.010

=head1 SYNOPSIS

envassert [options]

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

=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 Errors

There are three kinds of errors:

=over 8

=item ENV_ASSERT_MISSING_FROM_ENVIRONMENT

"Variable <var_name> is missing from environment"

=item ENV_ASSERT_INVALID_CONTENT_IN_VARIABLE

"Variable <var_name> has invalid content"

=item ENV_ASSERT_MISSING_FROM_DEFINITION

"Variable <var_name> is missing from description"

This error will only be reported if you have set
the special option B<exact>. See below.

=back

=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

=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/main/envassert.self-contained
    chmod +x ./envassert

=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<--version>

Prints the version 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

=item B<-x>, B<--exact>

Fail check if environment contains variables not defined in environment descript.
This option will override the equivalent option in .envdesc file.
Default: false

=back

=head1 EXAMPLES

    $ envassert
    Environment Assert: ERRORS:
        variables:
            FIRST_VAR: Variable FIRST_VAR is missing from environment
            FOURTH_VAR: Variable FOURTH_VAR is missing from environment

=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
