#!/usr/pkg/bin/perl
# -*- indent-tabs-mode: nil; -*-
# vim:ft=perl:et:sw=4
# $Id$

# Sympa - SYsteme de Multi-Postage Automatique
#
# Copyright (c) 1997, 1998, 1999 Institut Pasteur & Christophe Wolfhugel
# Copyright (c) 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005,
# 2006, 2007, 2008, 2009, 2010, 2011 Comite Reseau des Universites
# Copyright (c) 2011, 2012, 2013, 2014, 2015, 2016, 2017 GIP RENATER
# Copyright 2017, 2019 The Sympa Community. See the AUTHORS.md file at
# the top-level directory of this distribution and at
# <https://github.com/sympa-community/sympa.git>.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

use lib split(/:/, $ENV{SYMPALIB} || ''), '/usr/pkg/sympa/bin';
use strict;
use warnings;
use English qw(-no_match_vars);
use Getopt::Long;
use Pod::Usage;
use POSIX qw();

use Conf;
use Sympa::Constants;
use Sympa::Crash;    # Show traceback.
use Sympa::Log;
use Sympa::Mailer;
use Sympa::Process;
use Sympa::Spindle::ProcessOutgoing;
use Sympa::Spool::Listmaster;
use Sympa::Tools::Data;

my $process = Sympa::Process->instance;
$process->init(pidname => 'bulk');

## Check options
##  --debug : sets the debug mode
##  --foreground : prevents the script from beeing daemonized
##  --mail : logs every sendmail calls
my %options;
unless (
    GetOptions(
        \%main::options, 'config|f=s',  'debug|d', 'foreground|F',
        'help|h',        'log_level=s', 'mail|m',  'version|v',
    )
) {
    pod2usage(-exitval => 1, -output => \*STDERR);
}
if ($main::options{'help'}) {
    pod2usage(0);
} elsif ($main::options{'version'}) {
    printf "Sympa %s\n", Sympa::Constants::VERSION;
    exit 0;
}
$Conf::sympa_config = $main::options{config};

if ($main::options{'debug'}) {
    $main::options{'log_level'} = 2 unless $main::options{'log_level'};
    $main::options{'foreground'} = 1;
}

my $log = Sympa::Log->instance;
$log->{log_to_stderr} = 'all' if $main::options{'foreground'};

# Load sympa.conf
unless (Conf::load()) {
    die sprintf
        "Unable to load Sympa configuration, file %s or one of the virtual host robot.conf files contain errors. Exiting.\n",
        Conf::get_sympa_conf();
}

$log->openlog($Conf::Conf{'syslog'}, $Conf::Conf{'log_socket_type'});

my $mailer = Sympa::Mailer->instance;

# Enable SMTP logging if required
$mailer->{log_smtp} = $main::options{'mail'}
    || Sympa::Tools::Data::smart_eq($Conf::Conf{'log_smtp'}, 'on');

# Setting log_level using conf unless it is set by calling option.
if ($main::options{log_level}) {
    $log->{level} = $main::options{log_level};
    $log->syslog(
        'info',
        'Configuration file read, log level set using options: %s',
        $main::options{log_level}
    );
} else {
    $log->{level} = $Conf::Conf{'log_level'};
    $log->syslog(
        'info',
        'Configuration file read, default log level %s',
        $Conf::Conf{'log_level'}
    );
}

# Put ourselves in background if not in debug mode.
unless ($main::options{'foreground'}) {
    $process->daemonize;
}
$log->openlog($Conf::Conf{'syslog'}, $Conf::Conf{'log_socket_type'});

# Create and write the PID file.
$process->write_pid(initial => 1);
# If process is running in foreground, don't write STDERR to a dedicated file.
unless ($main::options{foreground}) {
    $process->direct_stderr_to_file;
}
## Set the User ID & Group ID for the process
$GID = $EGID = (getgrnam(Sympa::Constants::GROUP))[2];
$UID = $EUID = (getpwnam(Sympa::Constants::USER))[2];

## Required on FreeBSD to change ALL IDs(effective UID + real UID + saved UID)
POSIX::setuid((getpwnam(Sympa::Constants::USER))[2]);
POSIX::setgid((getgrnam(Sympa::Constants::GROUP))[2]);

## Check if the UID has correctly been set (useful on OS X)
unless (($GID == (getgrnam(Sympa::Constants::GROUP))[2])
    && ($UID == (getpwnam(Sympa::Constants::USER))[2])) {
    die
        "Failed to change process user ID and group ID. Note that on some OS Perl scripts can't change their real UID. In such circumstances Sympa should be run via sudo.\n";
}

## Sets the UMASK
umask(oct($Conf::Conf{'umask'}));

## Change to list root
unless (chdir($Conf::Conf{'home'})) {
    die sprintf 'Can\'t chdir to %s: %s', $Conf::Conf{'home'}, $!;
}

$log->syslog('notice', 'Bulk %s Started', Sympa::Constants::VERSION);

my $spindle = Sympa::Spindle::ProcessOutgoing->new(
    log_level => $main::options{log_level},
    log_smtp  => $main::options{mail},
);

## Catch signals, in order to exit cleanly, whenever possible.
$SIG{'TERM'} = 'sigterm';
$SIG{'INT'}  = 'sigterm';

$mailer->{redundancy} = $Conf::Conf{'bulk_max_count'} || 1;

while (not $spindle->{finish}) {
    $spindle->spin;
    last if $spindle->{finish};

    # Sleep for a while if bulk_mailer DB table is empty
    sleep $Conf::Conf{'bulk_sleep'};
}

# Purge grouped notifications
Sympa::Spool::Listmaster->instance->flush(purge => 1);

## Free zombie sendmail process.
#Sympa::Process->instance->reap_child;

$log->syslog('notice', 'Bulk exited normally due to signal');
$process->remove_pid;

exit(0);

## When we catch signal, just change the value of the loop
## variable.
sub sigterm {
    my ($sig) = @_;
    $log->syslog('notice',
        'Signal %s received, still processing current task', $sig);
    $spindle->{finish} = 'term';
}

# Moved to Sympa::Spindle::ProcessOutgoing::_trace_smime().
#sub trace_smime;

__END__

=encoding utf-8

=head1 NAME 

bulk, bulk.pl - Daemon for submitting messages to SMTP engine

=head1 SYNOPSIS

C<bulk.pl> S<[ C<--foreground> ]> S<[ C<--debug> ]>

=head1 DESCRIPTION 

This daemon must be run along with sympa_msg.pl(8).  It regularly checks the
content of outgoing (bulk) spool and submit the messages it finds in it to the
sendmail engine.  Several daemons may be used on deferent server for huge
traffic.

=head1 OPTIONS

=over 4

=item C<-d>, C<--debug>

Sets the debug mode

=item C<-f>, C<--config=>I<file>

Force bulk to use an alternative configuration file instead
of F</usr/pkg/etc/sympa/sympa.conf>.

=item C<-F>, C<--foreground>

Prevents the script from being daemonized

=item C<-h>, C<--help>

Prints this help message.

=item C<--log_level=>I<level>

Set log level.

=item C<-m>, C<--mail>

Logs every sendmail calls.

=back

=head1 FILES

F<$PIDDIR/bulk.pid> this file contains the process IDs
of F<bulk.pl>.

=head1 SEE ALSO

L<sympa.conf(5)>, L<sympa_msg(8)>.

L<Sympa::Spindle::ProcessOutgoing>.

=head1 HISTORY

bulk.pl initially written by Serge Aumont appeared on Sympa 6.0.

=cut
