#!/usr/bin/env perl

=head1 NAME

ww_purge_old_nonces   Delete nonce records from Key table for timestamps
	that are older than ten seconds.

=head1 SYNOPSIS

 ww_purge_old_nonces  course

=head1 DESCRIPTION

Deletes nonce records from the Key table if their timestamps
are more than 10 seconds old.


=head1 OPTIONS

=over

=item course

Course for which old nonces should be deleted.

=back

=cut

use strict;
use warnings;

BEGIN {
	use Mojo::File qw(curfile);
	use Env qw(WEBWORK_ROOT);

	$WEBWORK_ROOT = curfile->dirname->dirname;
}

use lib "$ENV{WEBWORK_ROOT}/lib";

use WeBWorK::CourseEnvironment;
use WeBWorK::DB;

use constant NONCE_LIFETIME => 21600; # 6 hours

sub usage {
	print STDERR "usage: $0  course \n";
	exit 1;
}

my ($course) = @ARGV;

usage() unless $course ;

my $ce = WeBWorK::CourseEnvironment->new({
	webwork_dir => $ENV{WEBWORK_ROOT},
	courseName  => $course,
});

my $db = WeBWorK::DB->new($ce);

my @errors;

my @listKeys = $db -> listKeys();

foreach my $user_id (@listKeys) {
	my $Key;
	eval { $Key = $db->getKey($user_id);};
	if ($@) { push @errors, "$user_id: ". $@ ;}
	else {
		if ($Key->key eq "nonce" &&
			(time()-$Key->timestamp > NONCE_LIFETIME)
		) {
			eval {$db->deleteKey($user_id);};
			if ($@) { push @errors, "$user_id: ". $@ ;}
		}
	}
}


if (@errors) {
	warn "The following errors occurred:\n", map { "* $_\n" } @errors;
	exit 1;
}
