#!/usr/bin/perl -w
use strict; # $Id: monm_smtp 119 2022-08-29 15:16:27Z abalama $
use utf8;

=encoding utf8

=head1 NAME

monm_smtp - SMTP checker for App::MonM

=head1 VERSION

Version 1.01

=head1 SYNOPSIS

    monm_smtp [ --port=PORTNUMBER ] [-t SECS] HOST

=head1 OPTIONS

=over 4

=item B<-h, --help>

Show short help information and quit

=item B<-H, --longhelp>

Show long help information and quit

=item B<-P PORTNUMBER, --port=PORTNUMBER>

Port number

Default: 25

=item B<-t SECT, --timeout=SECS>

Timeout value, secs

Default: 60

=back

=head1 DESCRIPTION

SMTP checker for App::MonM

=head1 DEPENDENCES

L<Net::SMTP>

=head1 AUTHOR

Serż Minus (Sergey Lepenkov) L<https://www.serzik.com> E<lt>abalama@cpan.orgE<gt>

=head1 COPYRIGHT

Copyright (C) 1998-2022 D&D Corporation. All Rights Reserved

=head1 LICENSE

This program is free software; you can redistribute it and/or
modify it under the same terms as Perl itself.

See L<https://dev.perl.org/licenses/>

=cut

use Getopt::Long;
use Pod::Usage;

use Net::SMTP;
use Try::Tiny;

use App::MonM::Const qw/
        IS_TTY SCREENWIDTH
        OK DONE ERROR SKIPPED PASSED FAILED UNKNOWN PROBLEM
    /;

use constant {
    HOST        => "localhost",
    PORT        => 25,
    TIMEOUT     => 60,
};

$SIG{INT} = sub { die "ABORTED\n"; };

$| = 1;  # autoflush

my $options = {};
Getopt::Long::Configure("bundling");
GetOptions($options,
    # Information
    "help|usage|h",         # Show help page
    "longhelp|H|?",         # Show long help page

    # General
    "port|P=i",                 # Port
    "timeout|time|t=i",         # Timeout

) || pod2usage(-exitval => 1, -verbose => 0, -output => \*STDERR);
pod2usage(-exitval => 0, -verbose => 1) if $options->{help};
pod2usage(-exitval => 0, -verbose => 2) if $options->{longhelp};

my $host        = shift(@ARGV) || HOST;
my $port        = $options->{port} || PORT;
my $timeout     = $options->{timeout} || TIMEOUT;

my $err = '';
try {
    my $smtp = Net::SMTP->new(
        Host    => $host,
        Timeout => $timeout,
        Port    => $port,
    );
    if ($smtp) {
        my $domainresult = $smtp->domain() || ''; # warn $smtp->message();
        $smtp->quit;
        $err = sprintf("SMTP domain not defined (host %s, port: %s)", $host, $port) unless $domainresult;
    } else {
        $err = sprintf("Host %s not reachable on port %s",$host, $port);
    }
}
catch {
    $err = $_;
};

if ($err) { 
    print STDERR $err, "\n";
    print ERROR, "\n";
    exit 1;
}

print OK, "\n";
exit 0;

__END__
