#!/usr/bin/perl
=comment
/****
* GLIST - LIST MANAGER
* ============================================================
* FILENAME
*	gfetch
* PURPOSE
*	Get a message from stdin and write it to a random filename
*	in the incoming queue.
* AUTHORS
*	Ask Solem Hoel <ask@unixmonks.net>
* ============================================================
* This file is a part of the glist mailinglist manager.
* (c) 2001 Ask Solem Hoel <http://www.unixmonks.net>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/
=cut

use strict;
use Fcntl qw(:flock);

die "Don't run as root!" unless $>; # $EUID
die "Shouldn't be run from console.\n" if -c '/proc/self/fd/0';

my $PREFIX = '@@PREFIX@@';
my $incoming = $PREFIX . '/spool/incoming';
my $filename;

my $locked_to = shift @ARGV;

# Generate a unique filename for the queue.
# loop until there is no file with that name in the queue.
while(1) {
	$filename = sprintf("%s/%.9d%.4d%.4d", 
		$incoming,
		time, 
		rand time, 
		rand time,
	);
	next if -l $filename;
	last unless -f $filename;
};

open(MESSAGE, ">$filename") || die "Couldn't create $filename: $!\n";
flock(MESSAGE, LOCK_EX);
my @file;
while(<STDIN>) {
	chomp;
	push(@file, $_);
};
if($locked_to) {
	unshift(@file, "--:#$locked_to");
}
for(my $i = 0; $i < scalar @file; $i++) {
	print MESSAGE $file[$i], "\n";
};
flock(MESSAGE, LOCK_UN);
close(MESSAGE) || die "Couldn't store $filename: $!\n";
chmod 0660, $filename;
