#!/usr/bin/perl -w
#
#   permutesesslog: output a random permutation of sessions from an
#                   httperf session log file
#   Copyright (C) 2004  Hewlett-Packard Company
#   Contributed by Yoshio Turner
#
#   This file is part of userver, a simple web server designed for
#   performance experiments.
#
#   See AUTHORS file for list of contributions.
#
#   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 2 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, write to the Free Software
#   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
#   02111-1307 USA
#

if (($#ARGV != 1) && ($#ARGV != 0)) {
    die "Usage: permutesesslog [logfile_name] integer_random_number_seed\n";
}

if ($#ARGV == 1) {
    $logfile = $ARGV[0];
    open(LF, "<$logfile") or die "open $logfile failed\n";
    $seed = $ARGV[1];
} else {
    open(LF, "<& STDIN") or die "couldn't dup STDIN\n";;
    $seed = $ARGV[0];
}

# read in all the sessions
$/ = ""; # sets input record separator to one blank line
$indx = 0;
while (<LF>) {
    $session[$indx++] = $_;
}
close LF;

# print out the random number seed in header info ("session" 0)
chomp($session[0]);
$session[0] .= "\n\#\n\# Permutelog Random Number Seed = $seed\n\n";
print $session[0];

# fix up the final session by appending a newline
$session[$indx-1] .= "\n";

if (!srand(int($seed))) {
    die "srand($seed) failed\n";
}

for ($i = 1; $i < $indx; $i++) {
    # choose a unique session
    do {
	$j = int(rand($indx-1));
    } until (!defined($chosen[$j]));
    $chosen[$j] = 1;
    chomp($session[$j+1]);

    # permute requests within the chosen session
    @sess = split('\n', $session[$j+1]);
    print "\# Session $i\n";
    @requestchosen = ();
    for ($k = 1; $k <= $#sess; $k++) {
	do {
	    $m = int(rand($#sess));
	} until (!defined($requestchosen[$m]));
	$requestchosen[$m] = 1;
	print "$sess[$m+1]\n";
    }
    print "\n" unless ($i == ($indx-1));
}

exit 0;
