#!/usr/bin/perl
#
# Strategy:
# Instead of using net_usr pipe via STDIN, we directly modify the
# database tables and files in the mail directory. I only don't know
# if Franta is using some kind of lock mechanism.
#
# Last updated: DL6RAI, Thu Dec 23 18:37:04 GMT 1999
# 
# Todo: make directories other than `mail' available too for sending mail
# Todo: Check if mail needs forwarding to another node, maybe by checking
#	for home nody entry.


require 'getopts.pl';

$prog = (split(/\//,$0))[-1];
$home = (getpwnam('clx_us'))[7];
$now = gmtime();
$db_name = "clx_db";
$psql = "psql -d $db_name -qtc";
$from = "system";

&Getopts('s:t:f:');

$to = lc($opt_t) if ($opt_t);
if (! $to) {
	print <<NNNN;
Usage: $prog -t <to> [-s <subject>] [-f <from>] <file>

This program is used to turn a file or STDIN into a mail message and
can be used to generate automated mail messages to users on your
system. 

Currently, mail messages are not being forwarded to other nodes.

At least an addressee must be stated using -t option.
NNNN
	exit 1;
}

$dir = "$home/box/mail/$to";

$from = lc($opt_f) if ($opt_f);
$subject = $opt_s if ($opt_s);

# See if postmaster is running
$qry = "";
$cmd = sprintf("%s \"%s\"",$psql,$qry);
$rc = system($cmd);
die "Cannot contact Postmaster - file cannot be sent.\n" if ($rc != 0);

if ($#ARGV < 0) { 
	$ARGV[0] = "-";  # read from STDIN
	$subject = "File transmission" if (! $opt_s);
}

foreach $filename (@ARGV) {

	if ( ! -f $filename && $filename ne '-' ) { 
		print "File $filename does not exist.\n";
		next;
	}

	$subject = $filename if (! $opt_s);
	open(IN,$filename);

	# get latest number from ml_dir, d_count
	$qry = "select d_count from ml_dir where d_name='mail'";
	$cmd = sprintf("%s \"%s\"",$psql,$qry);
	$nr = (`$cmd` % 99999) + 1; # 1-99999

	# update d_last (current date and time), latest number+1
	$qry = "update ml_dir set d_count=$nr, 
		d_last='$now' where d_name='mail'";
	$cmd = sprintf("%s \"%s\"",$psql,$qry);
	system("$cmd");

	# update ml_file, insert new message
	$qry = sprintf("insert into ml_file (f_name,f_thema,
		f_ldir,f_size,
		f_auth,f_titel,f_readc,f_date,f_dact) values
		('%d','mail','%s','-1','%s','%s','0','%s','%s')",
		$nr,$to,$from,$subject,$now,$now);
	$cmd = sprintf("%s \"%s\"",$psql,$qry);
	system("$cmd");

	# If necessary, Create a directory {adressee}
	# in the ~/box/mail directory.
	mkdir ($dir,0755) if ( ! -d  $dir);

	# Create a file named $nr in ~/box/mail/{addressee}
	$size = 0;
	$output = "$dir/$nr";
	open(OUT,"> $output") || die "cannot open $output\n";
	while(<IN>) {
		$size += length($_);
		print OUT $_;
	}

	# Update ml_file record with size now that we are done reading
	$qry = "update ml_file set f_size=$size where 
		f_name='$nr' and f_thema='mail'";
	$cmd = sprintf("%s \"%s\"",$psql,$qry);
	system("$cmd");

	close(IN);

	print("File $filename, size $size bytes sucessfully sent to $to as msg #$nr.\n");
}
