use Bugzilla;
use strict;

my $NUMBUGS      = 300_000;
my $STRFIELDS    = 10;
my $INTFIELDS    =  2;
my $METAFRACTION = .01;  # fraction of random strings with "meta" inserted

do 'globals.pl';

open WORDS, '/usr/share/dict/words'
    or die "Can't open /usr/share/dict/words: $!\n";
chomp(my @words = <WORDS>);
close WORDS;

my $dbh = Bugzilla->dbh;

my $strfieldname  = 'aa';
my $intfieldindex = 0;

my $strcols = join ", ",
              map "cf_" . $strfieldname++ . " TINYTEXT",
              1 .. $STRFIELDS;

my $intcols = join ", ",
              map "cf_int" . ++$intfieldindex . " INTEGER",
              1 ..  $INTFIELDS;

$dbh->do(qq{
    CREATE TABLE realcol (bug_id INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY,
                          $strcols, $intcols)
});

$dbh->do(qq{
    CREATE TABLE distcol_str (bug_id INTEGER NOT NULL,
                              field_id INTEGER NOT NULL,
                              value TINYTEXT,
                              PRIMARY KEY (bug_id, field_id),
                              INDEX (field_id))
});

$dbh->do(qq{
    CREATE TABLE distcol_int (bug_id INTEGER NOT NULL,
                              field_id INTEGER NOT NULL,
                              value INTEGER,
                              PRIMARY KEY (bug_id, field_id),
                              INDEX (field_id))
});

my $placeholders = join ',', ('?') x ($STRFIELDS + $INTFIELDS);

my $insert1 = $dbh->prepare(qq{
    INSERT INTO realcol VALUES (NULL, $placeholders)
});

my $insert2 = $dbh->prepare(qq{
    INSERT INTO distcol_str VALUES (?, ?, ?)
});

my $insert3 = $dbh->prepare(qq{
    INSERT INTO distcol_int VALUES (?, ?, ?)
});

my $lastins = $dbh->prepare(qq{
    SELECT LAST_INSERT_ID()
});

for (1 .. $NUMBUGS) {
    my @strings = map random_string(), 1 .. $STRFIELDS;
    my @ints    = map int(rand(1000)), 1 .. $INTFIELDS;
    $insert1->execute(@strings, @ints);
    $lastins->execute();
    my $bugid = $lastins->fetchrow_array();
    $insert2->execute($bugid, $_, $strings[$_])
        for 0 .. $STRFIELDS - 1;
    $insert3->execute($bugid, $_ + $STRFIELDS, $ints[$_])
        for 0 .. $INTFIELDS - 1;
}

sub random_string {
    my $string = join " ", map $words[ rand $#words ], 1 .. 10;
    if (rand() < $METAFRACTION) {
        substr($string, rand(length($string)), 0) = 'meta'
    }
    return $string;
}

