#!/usr/bin/perl

#
# usage: check_mail_address.pl mailbox@domain [--verbose] [--check-answer]
#

use strict;
use check_mail_address;

use Getopt::Long;
use Sys::Syslog qw(:DEFAULT setlogsock);
use File::Basename;

my($script_name) = File::Basename::basename($0);

##### configuration #####
my($default_max_attempts) = 1;

my(%syslog_param) = (
    'socket' => 'unix',
    'ident' => $script_name,
    'options' => 'cons,pid',
#    'facility' => 'local4',
    'facility' => 'mail',
    'priority' => 'notice',
# в logformat можно применять:
# %mailbox	- проверяемый mailbox
# %domain	- проверяемый домен
# %SMTP_host	- primary MX
# %SMTP_command	- команда, вливаемая MTA через сокет
# %SMTP_answer	- ответ MTA
# %check_result	- окончательный результат проверки
#    'logformat' => 'check %mailbox@%domain: %SMTP_command: %SMTP_answer; %check_result'
#    'logformat' => '%check_result (%mailbox@%domain: %SMTP_command => %SMTP_answer)'
    'logformat' => '%check_result (%mailbox@%domain: %SMTP_host => %SMTP_command => %SMTP_answer)'
);

##### /configuration #####

my($help, $debug, $verbose, $use_vrfy, $max_attempts);

GetOptions (
    'help'		=> \$help,
    'debug'		=> \$debug,
    'verbose'		=> \$verbose,
    'use-vrfy'		=> \$use_vrfy,
    'max-attempts=i'	=> \$max_attempts
);

my($address) = lc(shift(@ARGV));

if (($help) or (!$address)) {
    print("e-mail address checker

usage:
\t$script_name --help
\t$script_name --check-answer
\t$script_name <mail_addr> [--verbose|--debug] [--use-vrfy]
");
    exit();
}

$verbose = 1 if ($debug);
$max_attempts = $default_max_attempts unless ($max_attempts);

my($use_syslog) =
    ($syslog_param{'socket'}) &&
    ($syslog_param{'facility'}) &&
    ($syslog_param{'priority'}) &&
    (!$verbose);

if ($use_syslog) {
    setlogsock($syslog_param{'socket'});
    openlog($syslog_param{'ident'}, $syslog_param{'options'}, $syslog_param{'facility'});
}

my(@result) = verify_address($address, $use_vrfy, $max_attempts, ($use_syslog ? \%syslog_param : 0), $verbose);

if ($verbose) {
    print("'$result[0]': '$result[1]'");
} else {
    print($result[1]);
}

closelog() if ($use_syslog);

exit(0);
