#! /usr/bin/perl

use strict;
use warnings;
use Getopt::Long();
use English qw( -no_match_vars );
use Encode();
use Firefox::Marionette();

our $VERSION = '1.31';

sub _NUMBER_OF_SPACES_FOR_CODE_QUOTING_IN_MARKDOWN { return 4 }

sub _write_common_output {
    my ($certificate) = @_;
    my $indent = q[ ] x _NUMBER_OF_SPACES_FOR_CODE_QUOTING_IN_MARKDOWN();
    warn $indent
      . Encode::encode( 'UTF-8', $certificate->subject_name(), 1 ) . "\n";
    warn $indent
      . 'DB Key                   : '
      . $certificate->db_key() . "\n";
    warn $indent
      . 'Valid to                 : '
      . POSIX::strftime( '%d/%m/%Y', gmtime $certificate->not_valid_after() )
      . "\n";
    warn $indent
      . 'Certificate Serial Number: '
      . $certificate->serial_number() . "\n";
    warn $indent
      . 'SHA-1 Fingerprint        : '
      . $certificate->sha1_fingerprint() . "\n";
    warn $indent
      . 'SHA-256 Fingerprint      : '
      . $certificate->sha256_fingerprint() . "\n";
    return;
}

MAIN: {
    my %options;
    Getopt::Long::GetOptions( \%options, 'help', 'version', 'binary:s',
        'show-next' );
    if ( $options{help} ) {
        require Pod::Simple::Text;
        my $parser = Pod::Simple::Text->new();
        $parser->parse_from_file($PROGRAM_NAME);
        exit 0;
    }
    elsif ( $options{version} ) {
        print "$VERSION\n"
          or die "Failed to print to STDOUT:$EXTENDED_OS_ERROR\n";
        exit 0;
    }
    my %parameters;
    if ( $options{binary} ) {
        $parameters{binary} = $options{binary};
    }
    my $firefox = Firefox::Marionette->new(%parameters);
    my $now     = time;
    my $oldest;
    my $old_name;
    my $exit_code = 0;
    foreach my $certificate ( sort { $a->display_name() cmp $b->display_name }
        $firefox->certificates() )
    {
        if ( $certificate->is_ca_cert() ) {
            my $not_valid_after = $certificate->not_valid_after();
            if ( $not_valid_after < $now ) {
                warn Encode::encode( 'UTF-8', $certificate->display_name(), 1 )
                  . ' expired on '
                  . ( localtime $certificate->not_valid_after() ) . "\n";
                _write_common_output($certificate);
                $exit_code = 1;
            }
            elsif ( $certificate->not_valid_before > $now ) {
                warn Encode::encode( 'UTF-8', $certificate->display_name(), 1 )
                  . ' is not valid until '
                  . ( localtime $certificate->not_valid_before() ) . "\n";
                _write_common_output($certificate);
                $exit_code = 1;
            }
            elsif ( ( defined $oldest ) && ( $not_valid_after > $oldest ) ) {
            }
            else {
                $oldest   = $not_valid_after;
                $old_name = $certificate->display_name();
            }
        }
    }
    $firefox->quit();
    if ( $options{'show-next'} ) {
        print $old_name . ' will expire on ' . ( localtime $oldest ) . "\n"
          or die "Failed to print to STDOUT:$EXTENDED_OS_ERROR\n";
    }
    exit $exit_code;
}

__END__
=head1 NAME

check-firefox-certificate-authorities - check the CA certificates in firefox for expired certificates

=head1 VERSION

Version 1.31

=head1 USAGE

  $ check-firefox-certificate-authorities 

  $ check-firefox-certificate-authorities --binary=/path/to/new/firefox

=head1 DESCRIPTION

This program is intended to easily check firefox for expired CA certificates.

By default, the only firefox version that may be used will be present in the PATH environment variable.  However, the user may specify a different path with
the --binary parameter.

It will print out the display name of any CA certificates that are expired or not yet valid and if it finds expired certificates, it will exit with a non-zero exit code.

=head1 REQUIRED ARGUMENTS

None

=head1 OPTIONS

Option names can be abbreviated to uniqueness and can be stated with singe or double dashes, and option values can be separated from the option name by a space or '=' (as with Getopt::Long). Option names are also case-
sensitive.

=over 4

=item * --help - This page.

=item * --binary - Use this firefox binary instead of the default firefox instance

=item * --show-next - In addition to displaying any expired CA certificates, it will print out the next certificate that will expire and what date it will expire.

=back

=head1 CONFIGURATION

check-firefox-certificate-authorities requires no configuration files or environment variables.

=head1 DEPENDENCIES

check-firefox-certificate-authorities requires the following non-core Perl modules
 
=over
 
=item *
L<Pod::Simple::Text|Pod::Simple::Text>
 
=back

=head1 DIAGNOSTICS

None.

=head1 INCOMPATIBILITIES

None known.

=head1 EXIT STATUS

This program will exit with a zero after successfully completing.

=head1 BUGS AND LIMITATIONS

To report a bug, or view the current list of bugs, please visit L<https://github.com/david-dick/firefox-marionette/issues>

=head1 AUTHOR

David Dick  C<< <ddick@cpan.org> >>

=head1 LICENSE AND COPYRIGHT

Copyright (c) 2021, David Dick C<< <ddick@cpan.org> >>. All rights reserved.

This module is free software; you can redistribute it and/or
modify it under the same terms as Perl itself. See L<perlartistic/perlartistic>.

=head1 DISCLAIMER OF WARRANTY

BECAUSE THIS SOFTWARE IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE SOFTWARE, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE SOFTWARE "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER
EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE
ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE SOFTWARE IS WITH
YOU. SHOULD THE SOFTWARE PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL
NECESSARY SERVICING, REPAIR, OR CORRECTION.

IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE SOFTWARE AS PERMITTED BY THE ABOVE LICENCE, BE
LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL,
OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE
THE SOFTWARE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
FAILURE OF THE SOFTWARE TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.