#!/usr/bin/perl -w
###############################################################################
# SendMail Wrapper v2.1
# (c) ACENS TECHNOLOGIES
###############################################################################

#use strict;
use IO::File;
use File::Copy;
use POSIX qw(tmpnam);
use File::Basename;
use Time::localtime;

my @argline = <STDIN>;
my $lt = localtime();
my $mon = ( ($lt->mon)+1 ); $mon = "0" . $mon if ($mon < 10);
my $year = ( ($lt->year)+1900 );
my $day = $lt->mday; $day = "0" . $day if ($day < 10);
my $hour = $lt->hour; $hour = "0" . $hour if ($hour < 10);
my $min = $lt->min; $min = "0" . $min if ($min < 10);
my $sec = $lt->sec; $sec = "0" . $sec if ($sec < 10);
my $fech_now = $year  . $mon . $day;
my $flog_date = $day . "/" . $mon . "/" . $year; 
my $flog_now = $day . "/" . $mon . "/" . $year . "-" . $hour . ":" . $min . ":" . $sec;
my $logcntr = "/statistics/logs/mcount.log";
my $logqueue = "/statistics/logs/mail.log";
my $logerror = "/statistics/logs/mail-errors".".log";
my $tmpcntr = "";
my $tmpfh = "";
my $jmavisado= "/statistics/logs/avisado.chk";
my $jmspam= "/statistics/logs/spam";
my $mquota = "/etc/mquota";
my $contador = 0;
my $valido = 1;
my $truncado = '';
my $limite = 500;

if ( not -e $logerror ) {
    open(FILE, "> $logerror")    		or die "No se puede abrir $logerror: $!";;
    print FILE "::::" . ( basename($logerror) ) . " creado el " . $flog_now . "::::";
    print FILE  "\n";
    close(FILE);
}

if ( not -e $logcntr ) {
    open(FILE, "> $logcntr")			or die "No se puede abrir $logcntr: $!";   
    print FILE "::::" . ( basename($logcntr) ) . " creado el " . $flog_now . "::::";
    print FILE "\n\n";
    print FILE "[$flog_date] Mails enviados: $contador\n"; 
    close(FILE);
}

if ( not -e $logqueue ) {
    open(FILE, "> $logqueue")    		or die "No se puede abrir $logqueue: $!"; 
    print FILE "::::" . ( basename($logqueue) ) . " creado el " . $flog_now . "::::";
    print FILE  "\n";
    close(FILE);
}

open(STDERR, ">> $logerror");

if ( -e $mquota )  {
    open(MQUOTA, "< $mquota")			or die "No se puede abrir $mquota: $!";

    while (<MQUOTA>) {
        if ( /^(\d+)\t(\d+)\t(.*)$/ ) {
	    $limite=$2;
            last;
        }
    }
    close(MQUOTA);
}

open(COUNTER,$logcntr);

while (<COUNTER>) {
    if ( /^\[(.*)\] Mails enviados: (\d+)/ ) {
	
	$truncado='N';        

        if ( $flog_date eq $1) {
            if ( $2 > $limite ) {
                $valido=0; last;
            } else {
                $valido=1; last;
            }

        }
    } else {

        if ( (eof(COUNTER)) && ($truncado ne 'N') ){

	    print STDERR "$flog_now El contador $logcntr está truncado.\n";
	    $truncado='S';

	}
    }

}
close(COUNTER);

if ( $truncado eq 'S' ){
    open(FILE, "> $logcntr")                    or die "No se puede abrir $logcntr: $!";
    print FILE "::::" . ( basename($logcntr) ) . " REcreado el " . $flog_now . "::::";
    print FILE "\n\n";
    print FILE "[$flog_date] Mails enviados: $contador\n";
    close(FILE);    
}

if ( $valido ){
    open(SEND, "| /usr/sbin/sendmeall @ARGV") 	or die "Problemas de ejecucion del envio, revisa tu configuracion: $!\n";

    foreach (@argline) {
        print SEND;
    }
    close(SEND);
} 

open(LOG, ">> $logqueue") 			or die "No puedo abrir el fichero ".( basename($logqueue) ).":$!";

my $senderip = "";
my $dominio = "";
my $xmailer = "";
my $formulario = "";
my $accion = "";
my $receptor = "";
my $emisor = "";
my $atcount= 0;

foreach(@argline) {

    while ( /(.*)\@(.*)\.(\w+)/gi ) {
        $atcount++;
    }

    if ( /^Received: from (.*) by (.*) with/ ) { $senderip = $1; $dominio = $2; next; }; 
    if ( /^Received: from \[(.*)\]/ ) { $senderip = $1; }; 
    if ( /by (.*) \(/ ) { $dominio = $1; next; }; 
    if ( /^X-Mailer: (.*)/) { $xmailer = $1; next; }; 
    if ( /form="(.*)"/ ) { $formulario = $1; next; };
    if ( /action="(.*)"/ ) { $accion = $1; next; }; 
    if ( /http-referer (.*)\)/ ) { $formulario = $1; next; }; 
    if ( /script-name (.*)\)/ ) { $accion = $1; next; };
    if ( /^To: (.*)/ ) { $receptor = $1; next; };
    if ( /^From: (.*) \(/ ) { $emisor = $1; next; }; 
    if ( /^FROM: (.*)/ ) { $emisor = $1; next; };
    if ( /^Subject: (.*)/ ) { $subject = $1; next; };
}

if ( $valido ) {
    print LOG "++++ Envío realizado el $flog_now\n";
    print LOG "From: $emisor \| To: $receptor \| Subject: $subject\nEnvío desde: $senderip \| X-Mailer: $xmailer\nFormulario: $formulario$accion\n"; 
} else {
    print LOG "---- Envío bloqueado el $flog_now\n";
}

if (( $atcount >= 20 ) && ( not -e ( $jmspam . ".chk") )) {
    open(NOTIFY, "> $jmspam" ) or die "No se ha podido registrar caso de SPAM: $!\n";
    print NOTIFY "From: $emisor\nTo: $receptor\nSubject:  $subject\n\n- Envío realizado desde la IP $senderip a través de http://$dominio\n- X-Mailer utilizado: $xmailer\n- Formulario de envío utilizado: $formulario$accion\n\nContenidos:\n @argline\n";
    close(NOTIFY);
}     

close(LOG);

do { $tmpcntr = tmpnam() }
    until $tmpfh = IO::File->new($tmpcntr, O_RDWR|O_CREAT|O_EXCL) or warn "No es posible generar un nuevo archivo temporal.\n";

if ( -e $logcntr ) { 
    open(COUNTER, "< $logcntr") or warn "No puedo abrir el fichero ".( basename($logcntr) ).":$!";
} else {
    sleep(1);
    if ( -e $logcntr ) {
          open(COUNTER, "< $logcntr") or warn "No puedo abrir el fichero ".( basename($logcntr) ).":$!";
    }
}

open(TMPCNTR, "> $tmpcntr")                     or die "No puedo abrir el fichero ".( basename($tmpcntr) ).":$!";

while (<COUNTER>) {
    if ( /^\[(.*)\] Mails enviados: (\d+)/ ) {
        if ( $flog_date eq $1 ) {
            $contador = 1 + $2;
            if ( $valido ) {
                print TMPCNTR "[$flog_date] Mails enviados: $contador\n";
            } else {
                print TMPCNTR "[$flog_date] Mails enviados: $2. Limite de envios excedido.\n";
            }
    	    last;
        } else {
    	    if ( eof ) {
    	        $contador = 1;
                print TMPCNTR;
                if ($valido) {
                    print TMPCNTR "[$flog_date] Mails enviados: $contador\n";
                } else {
                    print TMPCNTR "[$flog_date] Mails enviados: $2. Limite de envios excedido.\n";
                }
                last;
	    } else {
	        print TMPCNTR;
	    }
        }
    } else {
        print TMPCNTR;
    }
}
close(COUNTER);
close(TMPCNTR);
move($tmpcntr,$logcntr)                     	or die "No puedo renombrar el fichero ".( basename($tmpcntr) ).":$!";
__END__
