package Mail::Run::Crypt;

# Force me to write this properly
use strict;
use warnings;
use utf8;

# Require this version of Perl
# 5.010 for defined-or operator
use 5.010;

# Import required modules
use Carp;
use Const::Fast;
use English '-no_match_vars';
use IPC::Run3;
use Mail::GnuPG;
use MIME::Entity;

# Specify package verson
our $VERSION = '0.03';

# Default exit value
const our $DEFAULT_EXIT => 127;

# Oldschool constructor
sub new {
    my ( $class, %opts ) = @_;

    # Blindly slurp in all the options given
    my $self = {%opts};

    # We must have a recipient
    exists $self->{mailto} and defined $self->{mailto}
      or croak 'mailto required';

    # Default the instance name to the package name if it wasn't given;
    # runcrypt(1) will pass it in
    $self->{name} //= $class;

    # We default to encrypting but not signing
    $self->{encrypt} //= 1;
    $self->{sign}    //= 0;

    # If signing, we need a key ID and a passphrase
    if ( $self->{sign} ) {
        exists $self->{keyid} and defined $self->{keyid}
          or croak 'keyid required for signing';
        exists $self->{passphrase} and defined $self->{passphrase}
          or croak 'passphrase required for signing';
    }

    # Return objectified self
    return bless $self, $class;
}

# Run a given command
sub run {
    my ( $self, @command ) = @_;

    # Run the command and wait for it to finish; keep its exit value for later
    my ( @out, @err );
    eval { run3 \@command, undef, \@out, \@err }
      or carp "command failed: $EVAL_ERROR";
    $self->{exit} = $CHILD_ERROR >> 8;

    # If there was output, mail it
    if (@out) {
        my $command = join q{ }, @command;
        my $subject = "$self->{name} output: $command";
        $self->_mail( $subject, \@out );
    }

    # If there were errors, mail them
    if (@err) {
        my $command = join q{ }, @command;
        my $subject = "$self->{name} errors: $command";
        $self->_mail( $subject, \@err );
    }

    # Return status reflecting the command exit value
    return $self->{exit} == 0;
}

# Return the value of the most recently run command, or 1 otherwise
sub bail { return shift->{exit} // $DEFAULT_EXIT }

# Send the message to the address in $ENV{MAILTO}
sub _mail {
    my ( $self, $subject, $content ) = @_;

    # Build MIME object with plaintext message
    my $mime = MIME::Entity->build(
        To      => $self->{mailto},
        Subject => $subject,
        Data    => $content,
    );

    # Encrypt the MIME object
    my $mgpg = Mail::GnuPG->new(
        key        => $self->{keyid},
        passphrase => $self->{passphrase},
    );

    # Sign and/or encrypt as appropriate
    if ( $self->{sign} and $self->{encrypt} ) {
        $mgpg->mime_signencrypt( $mime, $self->{mailto} );
    }
    elsif ( $self->{sign} ) {
        $mgpg->mime_sign( $mime, $self->{mailto} );
    }
    elsif ( $self->{encrypt} ) {
        $mgpg->mime_encrypt( $mime, $self->{mailto} );
    }

    # Send it
    return $mime->send();
}

1;

__END__

=pod

=for stopwords
mailserver decrypt runcrypt GPG OpenPGP tradename licensable MERCHANTABILITY
mailto keyid

=encoding utf8

=head1 NAME

Mail::Run::Crypt - Encrypt and mail output from command runs

=head1 VERSION

Version 0.03

=head1 DESCRIPTION

This module runs a system command with L<IPC::Run3|IPC::Run3>, and collects any
standard output and standard error it emits. If there is any standard output or
standard error content, it is encrypted and optionally signed with GnuPG, and
then each stream's content is mailed separately to a specified recipient
address.

The idea is to allow you to view the output of automated commands while having
the content encrypted as it passes through to your mailserver, and optionally
to have some assurance that the content was actually generated by the server
concerned. B<cron(8)> scripts are the ideal use case, but this would also work
with B<at(1)>, or anything else that might non-interactively run jobs for which
output is significant.

You will probably want to call this with the L<B<runcrypt(1)>|runcrypt> program
provided by this distribution, which includes a means to set the properties for
the module via environment variables or command line options.

=head1 SYNOPSIS

    use Mail::Run::Crypt;
    ...
    my $mrc = Mail::Run::Crypt->new(
        mailto => 'you@example.net',
    );
    $mrc->run($command, @args);
    ...
    my $mrc = Mail::Run::Crypt->new(
        sign       => 1,
        keyid      => '0x1234DEAD5678BEEF',
        passphrase => 'able was i ere i saw elba',
        mailto     => 'you@example.net',
    );
    $mrc->run($command, @args);
    
=head1 SUBROUTINES/METHODS

=head2 C<new(%opts)>

Constructor method; accepts the following named parameters:

=over 4

=item C<mailto>

The recipient email address for the content. This is always required.

=item C<encrypt>

Whether to encrypt the command output. This defaults to 1.

=item C<sign>

Whether to sign the command output. This defaults to 0. A C<keyid> and
C<passphrase> will be required for signing.

It is I<strongly> recommended that a dedicated key and passphrase be used for
signatures if this is needed. You should carefully consider the consequences of
a compromised key.

=item C<keyid>

The GnuPG key ID that should be used to sign messages. This is required for
signing, and has no effect without C<sign>. It can be any means of identifying
the key acceptable to GnuPG; the key's 16-byte ("long") hexadecimal ID prefixed
with C<0x> is probably the best way.

=item C<passphrase>

The passphrase used to decrypt the key. This is required for signing, and has
no effect without C<sign>.

=item C<name>

(Optional) The name of the object. When called from the
L<B<runcrypt(1)>|runcrypt> program, this will be the string "runcrypt".
Otherwise, it will default to this package's name.

=back

=head2 C<run(@command)>

Run the specified arguments as a command with L<IPC::Run3|IPC::Run3>, and email
any output or error content to the email recipient, encrypting and/or signing
as configured. Returns 1 if the command succeeded, 0 otherwise. Use
L<C<bail()>|/bail()> to get the actual exit code if needed.

=head2 C<bail()>

Return the exit status of the most recently run command, or 127 if no command
has been successfully run.

=head1 DIAGNOSTICS

=over 4

=item C<mailto required>

The required C<mailto> property was not passed in the constructor.

=item C<keyid required for signing>

Signing was specified, but no C<keyid> attribute was passed in the constructor.

=item C<passphrase required for signing>

Signing was specified, but no C<passphrase> attribute was passed in the constructor.

=item C<command failed: %s>

The command could not be run at all, raising the given error string. This is
typically due to problems finding the executable.

=back

=head1 CONFIGURATION AND ENVIRONMENT

You will need to have a functioning GnuPG public key setup for this to work,
including stored keys or a key retrieval system for your recipients. You will
also need a secret key if you want to sign the messages.

You should I<definitely not> use your personal key for this; generate one
specifically for mail signing and encryption instead.

I wrote a tutorial on GnuPG key setup, including agent configuration, as part
of this series:

L<https://sanctum.geek.nz/arabesque/series/gnu-linux-crypto/>

=head1 DEPENDENCIES

=over 4

=item *

Perl v5.10.0 or newer

=item *

L<Carp|Carp>

=item *

L<Const::Fast|Const::Fast>

=item *

L<English|English>

=item *

L<IPC::Run3|IPC::Run3>

=item *

L<Mail::GnuPG|Mail::GnuPG>

=item *

L<MIME::Entity|MIME::Entity>

=back

=head1 INCOMPATIBILITIES

This module uses L<Mail::GnuPG|Mail::GnuPG> and other GnuPG-specific code, so
it won't work with other OpenPGP implementations.

=head1 BUGS AND LIMITATIONS

Definitely. This code is not production-ready. In particular, there is almost
no test suite.

=head1 AUTHOR

Tom Ryder C<< <tom@sanctum.geek.nz> >>

=head1 LICENSE AND COPYRIGHT

Copyright (C) 2017 Tom Ryder

This program is free software; you can redistribute it and/or modify it under
the terms of the Artistic License (2.0). You may obtain a copy of the full
license at:

L<http://www.perlfoundation.org/artistic_license_2_0>

Any use, modification, and distribution of the Standard or Modified Versions is
governed by this Artistic License. By using, modifying or distributing the
Package, you accept this license. Do not use, modify, or distribute the
Package, if you do not accept this license.

If your Modified Version has been derived from a Modified Version made by
someone other than you, you are nevertheless required to ensure that your
Modified Version complies with the requirements of this license.

This license does not grant you the right to use any trademark, service mark,
tradename, or logo of the Copyright Holder.

This license includes the non-exclusive, worldwide, free-of-charge patent
license to make, have made, use, offer to sell, sell, import and otherwise
transfer the Package with respect to any patent claims licensable by the
Copyright Holder that are necessarily infringed by the Package. If you
institute patent litigation (including a cross-claim or counterclaim) against
any party alleging that the Package constitutes direct or contributory patent
infringement, then this Artistic License to you shall terminate on the date
that such litigation is filed.

Disclaimer of Warranty: THE PACKAGE IS PROVIDED BY THE COPYRIGHT HOLDER AND
CONTRIBUTORS "AS IS' AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES. THE IMPLIED
WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR
NON-INFRINGEMENT ARE DISCLAIMED TO THE EXTENT PERMITTED BY YOUR LOCAL LAW.
UNLESS REQUIRED BY LAW, NO COPYRIGHT HOLDER OR CONTRIBUTOR WILL BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING IN ANY WAY
OUT OF THE USE OF THE PACKAGE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
DAMAGE.

=cut
