#!/usr/bin/perl
# SPDX-License-Identifier: MIT
#
# Generate a bunch of emails, as mbox format.
#
#     genmails [-n #messages] [-l #linespermsg] [-w #wordsperline]
#
# Few words, many messages: genmails -n1000
# Many words, few messages: genmails -l10 -w6

use Getopt::Long;
use POSIX qw(strftime);
use strict;
use warnings;
my($count, $lines, $wordsperline, $dict) = (1, 1, 2);

sub read_dict
{
	my $fh;
	if (!open($fh, "<", $_[0])) {
		print STDERR "cannot read wordlist $_[0]: $!\n";
		return;
	}
	<$fh>;
	my @dict;
	while (<$fh>) {
		chomp;
		my $pos = index($_, '/');
		if ($pos >= 0) {
			substr($_, $pos) = "";
		}
		if (length($_) > 0) {
			push(@dict, $_);
		}
	}
	if (scalar(@dict) == 0) {
		@dict = ("bweebol");
	}
	return \@dict;
}

sub pick_word
{
	return $dict->[int(rand() * scalar(@$dict))];
}

sub mkdate
{
	my @wkstr = qw(Sun Mon Tue Wed Thu Fri Sat);
	my @mostr = qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec);
	my @now   = gmtime(shift @_);

	return $wkstr[$now[6]].", ".$now[3]." ".$mostr[$now[4]].
	       strftime(" %Y %H:%M:%S +0000", @now);
}

&Getopt::Long::Configure(qw(bundling));
&GetOptions("n=i" => \$count, "l=i" => \$lines, "w=i" => \$wordsperline);
$dict = &read_dict("/usr/share/hunspell/en_US.dic");
my $now = time();
for (my $i = 0; $i < $count; ++$i) {
	print "From user\@example.com ", scalar(localtime($now)), "\n";
	print "From: <user\@example.com>\n";
	print "To: <user\@example.com>\n";
	print "Date: ", &mkdate($now - $count + $i), "\n";
	my $word1 = &pick_word();
	my $word2 = &pick_word();
	my $word3 = &pick_word();
	print "Message-ID: <g-$now-$$-$i\@example.com>\n";
	print "Content-Type: text/plain; charset=utf-8\n";
	print "MIME-Version: 1.0\n";
	print "Subject: $i $word1 $word2\n\n";
	for (my $j = 0; $j < $lines; ++$j) {
		for (my $k = 0; $k < $wordsperline; ++$k) {
			print &pick_word(), " ";
		}
		print "\n";
	}
	print "\n";
}
