use Benchmark;
use Apache::Session::Flex;
use Getopt::Long;
use strict;

my %options;
# Get command line options
if ( !GetOptions(\%options,'debug','times=i','store=s','delete') ) {
	die "Usage: perl $0 --debug --times=N --store=File|SharedMem|Memcached|MySQL|DB_File --delete\n";
}

$options{store} ||= 'File';
$options{times} ||= 100;

my $value = [
	1,2,3,4,5,6,7,8,9
];
my %flex_options;

if ( $options{store} eq 'File' ) { 
	%flex_options = (
                Store     => 'File',
                Directory => '/tmp/apache-session-memcached'
	);
}
elsif ( $options{store} eq 'Memcached' ) {
	%flex_options = (
                Store     => 'Memcached',
                Servers   => '127.0.0.1:20000'
	);
}
elsif ( $options{store} eq 'SharedMem' ) {
        %flex_options = (
                Store     => 'SharedMem',
	);
}
elsif ( $options{store} eq 'MySQL' ) {
	%flex_options = (
		Store => 'MySQL',
		DataSource => 'dbi:mysql:database=sessions',
		UserName => 'sesman',
		Password => 'sesman'
	);
}
elsif ( $options{store} eq 'DB_File' ) {
	%flex_options = (
		Store => 'DB_File',
		FileName => '/tmp/apache-session-memcached/session.db' 
	);
}

my $t0 = new Benchmark;
for ( my $i = 0; $i < $options{times}; $i++ ) {
	my $session;
	my $sid;

	# Creates
	tie %{$session}, 'Apache::Session::Flex', undef, {
		Lock      => 'Null',
		Generate  => 'MD5', 
		Serialize => 'Storable',
		%flex_options
	};
	my $sid = $session->{_session_id};
	$session->{foo} = $value;
	untie %{$session};

	# Reads
	tie %{$session}, 'Apache::Session::Flex', $sid, {
		Lock      => 'Null',
		Generate  => 'MD5',
		Serialize => 'Storable',
		%flex_options
	};
	# Deletes || unties
	$options{delete} ? tied(%{$session})->delete : untie %{$session};
}

my $t1 = new Benchmark;
my $td = timediff($t1, $t0);
print "\n----------------\nStore: $options{store}, Times: $options{times}\n----------------\nthe code took:",timestr($td),"\n";

if ( $options{store} eq 'SharedMem' ) {
	require IPC::Cache;
	IPC::Cache::CLEAR();
}
