#!/usr/local/bin/perl
#
use Jcode;
use MIME::Base64;
use MIME::QuotedPrint;

$tmpfile = "/var/tmp/htmlchopper.$$";
$match = "[A-Za-z0-9\-\.\_]+@[A-Za-z0-9\-\_]+\.[A-Za-z0-9\-\.\_]+";

$inhead = 1; $multi = 0; $skip = 0; $encsect = 0; $maintext = 0; $single =0;
$bflag = 0; $enc = 0; $boundary = "";

open (TFILE, ">$tmpfile") || die;
while (<STDIN>) {
  if($inhead){
       if(/^\s*$/){
           print TFILE $_;
           $inhead = 0;
           if($multi == 1){
                $skip = 1;
                $boundary =~ s/^.*;\s*boundary\s*=\s*"?([^"]+)"?/$1/;
                if($from =~ /($match)/){
                    $from = $1;
                    $from =~ s/\@/\\@/;
                    system("/bin/cat /home/messg/warning.txt | /usr/bin/mail -s Warning_Mail $from");
                }
            }else{$single = 1;}
           next;
        }
        if (/^From:/) { $from = $_; $from =~ s/From://g;}
        if(/Encoding/i){
               if(/Base64/i){$enc = 1;s/Base64/7bit/i;}
               if(/quoted-printable/i){$enc = 2;s/quoted-printable/7bit/i;}
        }

       if (/^Content-Type:\s*multipart\/alternative/i || $bflag && /boundary/) {                s/\r\n/\n/g;  s/\r/\n/g;   s/\n//g;
		$boundary .= $_;
                $multi = 1;
		if($bflag){$bflag = 0;}else{$bflag = 1;} 
	}
        print TFILE $_;
   }

  if ($skip) {
       if (/$boundary/i){
           print TFILE $_;
           $skip = 0; $encsect = 1;
           next;
       }
  }

  if($encsect){
       if(/^\s*$/){
          print TFILE $_;
          $encsect = 0; $maintext = 1; 
          next; 
       }
       if (/^Content-Transfer/i){
          if(/Base64/i){$enc = 1;s/Base64/7bit/i;}
          if(/quoted-printable/i){$enc = 2;s/quoted-printable/7bit/i;}
       }
     print TFILE $_;
  }

  if($maintext){
        last if (/$boundary/i);
        s/\r\n/\n/g;   s/\r/\n/g;
        if($enc == 1){$_ = decode_base64($_);}
        if($enc == 2){$_ = decode_qp($_);}
        s/\r\n/\n/g;   s/\r/\n/g;
        print TFILE $_;
  }

  if($single){
        if($enc == 1){$_ = decode_base64($_);}
        if($enc == 2){$_ = decode_qp($_);}
	print TFILE $_;
  }
}

close(TFILE);
system("/bin/cat $tmpfile");
unlink($tmpfile);
exit(0);

