#!/usr/bin/perl

#----------------------------------------------------------------------
# Generate a random mbox
# Copyright © 2019 Guilhem Moulin <guilhem@fripost.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# 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, see <https://www.gnu.org/licenses/>.
#----------------------------------------------------------------------

use warnings;
use strict;

use Time::HiRes ();
use POSIX qw{strftime setlocale};
use Crypt::URandom "urandom";

setlocale(POSIX::LC_TIME, "C");

foreach (qw/cur new tmp/) {
    my $d = $ARGV[0] ."/". $_;
    mkdir $d, 0700 or die "mkdir: $!"
}

my $NEW = $ARGV[0] ."/new";
for (my $i = 0; $i < $ARGV[1]; $i++) {
    my $timestamp = Time::HiRes::gettimeofday();
    my $filename = sprintf("%10d.M%010d.localhost", $timestamp, $i);
    open my $out, ">", $NEW ."/". $filename or die "open: $!";

    my $message_id = sprintf "%.10f\@example.net", $timestamp;
    my $sender = unpack("H*", urandom(8))."\@example.net";
    print $out
          "From: <$sender>\r\n"
        . "To: <recipient\@example.net> \r\n"
        . "Subject: Hello world! \r\n"
        . "Date: ". strftime("%a, %e %b %Y %H:%M:%S %z", localtime($timestamp)). "\r\n"
        . "Message-ID: ". sprintf("<%.10f\@example.net>", $timestamp)."\r\n"
        . "\r\n";

    my $len = 1 + int(rand(4095));
    my $body = unpack("H*", urandom($len));
    for (my $i = 0; $i < 2*$len; $i += 70) {
        print $out substr($body, $i, 70), "\r\n";
    }
    close($out);
}
