#! /usr/bin/perl

# distr.pl 199703062030

# Example of a sendfiled post processing filter
# =======
#
# Insert the following line to /usr/local/etc/sendfile.aliases:
#
# distrtest    <username> | <path>/distr.pl
#
#
# Use the right strings instead of <username> and <path>. Modify the
# distribution list in the global section of this source.
#

# History
#
# * 1997-03-31T13:30+02 Stefan Scholl <stesch@sks.inka.de
#   - New version of readsafthead()
# * 1997-03-06T21:30+01 Stefan Scholl <stesch@sks.inka.de>
#   - Some minor code cleanup
#   - read() instead <STDIN> in read-loop
# * 1997-03-03T20:26+01 Stefan Scholl <stesch@sks.inka.de>
#   - Use the module Unicode::Utf7
#   - Insert comment (and forward the old one, too)
# * 1997-02-01T16:45+01 Stefan Scholl <stesch@sks.inka.de>
#   - First Version

use Unicode::Utf7 qw( utf7toiso );


#-globals---------------------------------------------------

# SAFT-Urls for all receivers
@distlist = qw( saft://parsec.inka.de/stesch saft://bofh.belwue.de/framstag );

$tempdir      = $ENV{'TMPDIR'} or $tempdir  = '/tmp';
$gzippath     = '/usr/local/bin/gzip';
$sendfilepath = '/usr/local/bin/sendfile';
$PACKET       = 512;

#-----------------------------------------------------------


# Sideeffect: result is in %shead

sub readsafthead {
    my $l;

    while($l = <STDIN>) {
        my ($key, $val);
	
	$l =~ tr/\r\n//d; # get rid of CRs and LFs.
        ($key, $val) = split(/\s+/, $l, 2);
	return if uc($key) eq 'DATA';
	$shead{uc($key)} = utf7toiso($val);
    }
}


#-----------------------------------------------------------


#-main------------------------------------------------------


# Reading the header into %shead. Following data on STDIN is
# the transfered file.
&readsafthead;

# Comment
if(defined($shead{'COMMENT'})) {   # There's allready a comment
    $comment = "forward from $shead{FROM}\r\n$shead{'COMMENT'}";
} else {
    $comment = "forward from $shead{FROM}";
}





if($shead{'TYPE'} =~ /COMPRESSED/i) {
    $outf = "|$gzippath -dc >$shead{FILE}";
} else {
    $outf = ">$shead{FILE}";
}



chdir($tempdir);

if(open(OUT, $outf)) {
    my $data;
    
    while(read(STDIN, $data, $PACKET)) {
        print OUT $data;
    }
    close(OUT);
    
    # Now we have the received file in $tempdir.
    
    # Time to distribute it.
    
    foreach $receiver (@distlist) {
        system("$sendfilepath $shead{FILE} -c '$comment' $receiver");
    }
    
    # get rid of it!
    unlink($shead{FILE});
    
} else {
    # right place for error logging. :-)
}

#-----------------------------------------------------------
