#! /usr/bin/perl
# -*- indent-tabs-mode: nil; -*-
# vim:ft=perl:et:sw=4
# $Id: upgrade_send_spool.pl.in 12612 2016-01-01 01:48:29Z sikeda $

# 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 GIP RENATER
#
# 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/local/libdata/perl5/site_perl';
use strict;
use warnings;
use Digest::MD5;
use English qw(-no_match_vars);
use Getopt::Long;
use Pod::Usage;

use Sympa::Bulk;
use Sympa::Constants;
use Conf;
use Sympa::Log;
use Sympa::Spool;
use Sympa::Spool::Incoming;

my %options;
unless (GetOptions(\%options, 'help|h', 'dry_run', 'version|v')) {
    pod2usage(-exitval => 1, -output => \*STDERR);
}
if ($options{'help'}) {
    pod2usage(0);
} elsif ($options{'version'}) {
    printf "Sympa %s\n", Sympa::Constants::VERSION;
    exit 0;
}

my $log = Sympa::Log->instance;

unless (Conf::load(Conf::get_sympa_conf(), 'no_db')) {
    die sprintf 'Configuration file %s has errors.\n', Conf::get_sympa_conf();
}

# 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.";
}
# Sets the UMASK
umask oct $Conf::Conf{'umask'};

my $bulk      = Sympa::Bulk->new;
my $spool     = Sympa::Spool::Incoming->new;
my $spool_dir = $spool->{directory};

mkdir "$spool_dir/moved", 0755 unless -d "$spool_dir/moved";

while (1) {
    my ($message, $handle) = $spool->next;

    if ($message and $handle) {
        my $status = process($message);
        unless (defined $status) {
            $spool->quarantine($handle) unless $options{dry_run};
        } elsif ($status) {
            $handle->rename($spool_dir . '/moved/' . $handle->basename)
                unless $options{dry_run};
        } else {
            next;
        }
    } elsif ($handle) {
        next;
    } else {
        last;
    }
}

sub process {
    my $message = shift;

    return 0 unless $message->{checksum};

    ## valid X-Sympa-Checksum prove the message comes from web interface with
    ## authenticated sender
    unless ($message->{'checksum'} eq sympa_checksum($message->{'rcpt'})) {
        $log->syslog('err', '%s: Incorrect X-Sympa-Checksum header',
            $message);
        return undef;
    }

    if (ref $message->{context} eq 'Sympa::List') {
        $message->{'md5_check'} = 1;
        delete $message->{checksum};

        # Don't use method of incoming spool to preserve original PID.
        Sympa::Spool::store_spool($spool_dir, $message, '%s@%s.%ld.%ld,%d',
            [qw(localpart domainpart date pid RAND)])
            unless $options{dry_run};
        $log->syslog('info', '%s: Moved to msg spool', $message);
    } else {
        $bulk->store($message, [split /\s*,\s*/, $message->{rcpt}])
            unless $options{dry_run};
        $log->syslog('info', '%s: Moved to bulk spool', $message);
    }
    return 1;
}

sub sympa_checksum {
    my $rcpt = shift;
    return (
        substr(
            Digest::MD5::md5_hex(join('/', $Conf::Conf{'cookie'}, $rcpt)), -10
        )
    );
}

__END__

=encoding utf-8

=head1 NAME

upgrade_send_spool, upgrade_send_spool.pl - Upgrade messages in incoming spool

=head1 SYNOMSIS

  upgrade_send_spool.pl [ --dry_run ]

=head1 DESCRIPTION

On Sympa earlier than 6.2, messages sent from WWSympa were injected in
msg spool with special checksum.
Recent release of Sympa and WWSympa injects outbound messages in outgoing
spool or sends them by Mailer directly.
This program migrates messages with old format in appropriate spools.

=head1 OPTIONS

=over

=item --dry_run

Shows what will be done but won't really perform upgrade process.

=back

=head1 RETURN VALUE

This program exits with status 0 if processing secceeded.
Otherwise exits with non-zero status.

=head1 CONFIGURATION OPTIONS

Following site configuration parameters in F</var/sympa/etc/sympa.conf> are referred.

=over

=item cookie

=item queue

=item umask

=back

=head1 SEE ALSO

L<sympa.conf(5)>, L<Sympa::Message>.

=head1 HISTORY

upgrade_send_spool.pl appeared on Sympa 6.2.

=cut
