#!/usr/bin/perl 

########## Confixx(R) 3.0 Professional ############
####### Copyright SWsoft, Inc. 2004-2005 ##########
#### http://www.sw-soft.com - info@sw-soft.com ####


## Globale Variablen

$db_address = "DBI:mysql:confixxtest:localhost";
$dbUser = "root";
$dbPw = "";
$SENDMAIL = "/usr/sbin/sendmail";
$ar_id = "Confixx Autoresponder";

## /Globale Variablen

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

Getopt::Long::Configure('prefix_pattern=--|-','ignore_case');

@config_opts = (
  'i|ident=i',
  'd|debug=i',
  'help',
  'h',
  'l|log=s',
  'v|version'
);

my %args =();

unless( &GetOptions(\%args, @config_opts) ){
  pod2usage({ -msg => "$0: Errors in the command line found",
	-exitval => 1} );
}

if ( $args{'h'} ){
  pod2usage( -exitval => 0);
}

if ( $args{'v'} ){
  print "\nautoresponder.pl Confixx v.3.00\n";
  exit 0;
}
  
if ($args{'help'}){
  pod2usage( -verbose => 2, -exitval => 0);
}
  
$ident = $args{'i'}||$ARGV[0];
unless ($ident ne "" && $ident =~ /^\d+$/){  
  pod2usage( {-msg => "\n$0: Error: no ident given\n", 
	-exitval => 2} );
}

$debug=$args{'d'}||0;

$log=$args{'l'}||'';
if ($log && open(LOG,">>$log")){
  close(LOG);
}else{
  $log='';
}


&debugMsg("ident: $ident",1);

$MID = '';
&header_holen;
($mail{'To'} ne "") || die("Keine Absender-Adresse gefunden.\n");
$dbh = DBI->connect($db_address, $dbUser, $dbPw)
  or die("Konnte Datenbank nicht öffnen\n$DBI::errstr\n");
&db_abfrage && &respond;
$dbh->disconnect
  or die("Konnte Datenbankverbindung nicht schließen\n$DBI::errstr\n");



## Unterprogamme

sub debugMsg{
  my($msg,$dl)=@_;
  $dl||=0;	
  if ($dl<=$debug && $msg){
	print $msg,"\n";
	if($log){
	  my($sec,$min,$hour,$mday,$mon)=localtime;
	  $mon++;
	  open (LOG,">>$log");
	  print LOG "$mon.$mday $hour:$min:$sec $msg\n";
	  close LOG;
	}  	
  }
}

sub header_holen{
  my($weiter, $h_sender, $h_from, $h_returnpath, $h_replyto);
  $weiter = 1;
  my $exitCause='';
  
  &debugMsg("\tStart header:",2);
  while (<STDIN>){
	
	if($weiter){
      if ($_ =~ /^\n$/){
        $weiter = 0;
      }
      elsif($_ =~ /^Sender: (.*<?\S+\@\S+)\n$/){
        $h_sender = $1;
      }
      elsif($_ =~ /^Sender: <>\n$/){
        $exitCause="1:$_";
      }
      elsif($_ =~ /^From: (.*<?\S+\@\S+)\n$/){
        $h_from = $1;
      }
      elsif($_ =~ /^From: (\S+\@\S+ \(.*\))\n$/){
        $h_from = $1;
      }
      elsif($_ =~ /^From: .*MAILER-DAEMON/i){
        $exitCause="2:$_";
      }
      elsif($_ =~ /^From: .*Mail Delivery (Sub)?system/i){
        $exitCause="3:$_";
      }
      elsif($_ =~ /^Return-Path: (.*<?\S+\@\S+)\n$/){
        $h_returnpath = $1;
      }
      elsif($_ =~ /^Return-Path: <>\n$/){
        $exitCause="4:$_";
      }
      elsif($_ =~ /^Reply-To: (.*<?\S+\@\S+)\n$/){
        $h_replyto = $1;
      }
      elsif($_ =~ /^To:.*\s+<?(\S+\@\S+\w)>?\n$/){
        $rcpt = $1;
      }
      elsif($_ =~ /^Subject: (.*)\n$/){
        $mail{'Subject'} = $1;
        if($mail{'Subject'} =~ /^Delivery Status Notification \(Failure\)$/i){
      	  $exitCause="5:Subject: $mail{'Subject'}\n";
        }
      }
        elsif($_ =~ /^Precedence: (junk|list|bulk|autoreply)\n$/i){
        $exitCause="6:$_";
      }
      elsif($_ =~ /^X-Mailer: \Q$ar_id\E\n$/i){
        $exitCause="7:$_";
      }
			elsif( $_ =~ /^\s+report-type=delivery-status;\n$/ ) {
        $exitCause = "8:$_";
			}
      elsif($_ =~ /^Message-ID: (<\S+>)\n$/){
        $MID = $1;
      }
	  if ($exitCause){
		&debugMsg("Exit: $exitCause",1);
		exit 0;
	  }

	  chomp;
	  &debugMsg($_,2);

    }
    else{
      next;
    }
  }
  &debugMsg("\tStop header.",2);

  $mail{'To'} = 
        $h_replyto
        || $h_from
        || $h_sender;

  &debugMsg("To: $mail{'To'}",1);

  if(!$mail{'To'} || $mail{'To'} =~ /MAILER-DAEMON\@\S+/i){
	&debugMsg("Exit: Bad to-adress\n",1);
    exit 0;
  }
}


sub db_abfrage{
  my($sth, @row, $weiter, $check_from, $check_to, $to);
  $mail{'To'} =~ /<?(\S+\@\S+\w)>?$/;
  $to = $1;
  $to =~ tr/A-Z/a-z/;
  $rcpt =~ tr/A-Z/a-z/;
  use DBI;
  $sth = $dbh->prepare("SELECT negvon, von, link, negrcpt, rcpt, absenderemail, emailtext, emailbetreff, kunde, absendername FROM autoresponder WHERE ident='$ident';");
  $sth->execute or die("#2002: $DBI::errstr");
  @row = $sth->fetchrow_array or die("#2003: $DBI::errstr");
  $sth->finish;
  $weiter = 1;

  if($weiter){
    $mail{'Message'} = $row[6];
    $mail{'Message'} =~ s/\r//g;
    $mail{'From'} = $row[5];
    $user = $row[8];
    $mail{'name'} = $row[9];
    if ($row[7] eq ""){
      $mail{'Subject'} = "Re: $mail{'Subject'}";
    }
    else{
      $mail{'Subject'} = $row[7];
    }
  }
  
  &debugMsg("From: $mail{'From'}",1);
  
  return($weiter);
}


sub respond{
  my ($time, $mail, $From);
  if ($mail{'name'} eq ""){
    $From = $mail{'From'};
  }
  else{
    $From = "\"$mail{'name'}\" <$mail{'From'}>";
  }

  my $msgid = $MID ? "Message-ID: $MID\n" : "";

  $mail = "From: $From\nTo: $mail{'To'}\nSubject: $mail{'Subject'}\nX-Mailer: $ar_id\nPrecedence: junk\n$msgid\n$mail{'Message'}\n";

  if (open(MAIL, "|$SENDMAIL -ti -f $mail{'From'}")){
    print MAIL $mail;
	close(MAIL);
	
	&debugMsg("OK\n",1);
  }else{
	&debugMsg($?,0);
  }	
}
## /Unterprogamme

__END__

=head1 NAME

autoresponder.pl - the tool of Confixx. Version 3.00

=head1 SYNOPSIS

autoresponder.pl <ident> [options] 

B<ident>:           the autoresponders ident

options:            --ident E<verbar> --log E<verbar> --debug E<verbar> --version E<verbar> --help 

=head1 OPTIONS

=over 4

=item E<lt>B<ident>E<gt>

the ident number  of autoresponder

=item B<-l|--log>

the path to log-file

=item B<-d|--debug>

the debug level. Default 0

=item B<--help>

full documentation

=back                

=head1 USAGE

in F<aliases>:

confixx-du-E<lt>identE<gt>: "|/usr/bin/autoresponder.pl <ident>"

=cut
