#!@PERL@
#
# Monitor the status of a CIVS election server. The URL of this script
# should be kept private.

use strict;
use warnings;

use lib '@CGIBINDIR@';
# use admctrl;
use civs_common;

use CGI qw(:standard -utf8);
use Encode qw(encode decode);
use URI::Escape;
use File::stat;
use DB_File;
use POSIX qw(strftime);
undef $/;

&HTML_Header("CIVS Server Status");
&CIVS_Header("Server Status");

if (param('key') ne '@ADMIN_KEY@') {
    print p("Password missing or wrong");
    exit 1;
}
my $elections_dir = $home."/elections/";
opendir(DIR, $elections_dir) or die "Can't open directory $elections_dir: $!";

my @entries;

my $total_users = 0;
my $total_auth = 0;
my $num_polls = 0;

while (defined(my $file = readdir(DIR))) {
    next if !defined($file);
    next if $file =~/^\.\.?$/;    # skip . and ..
    next unless -d "$elections_dir/$file";   # skip non-directories
    next unless $file =~ m/^E_[0123456789abcdef]+/;   # skip non-elections

    $num_polls++;
    my $election_dir = "$elections_dir/$file";
    my $election_data = $election_dir."/election_data";
    my $vote_data = $election_dir."/vote_data";
    my $started_file = $election_dir."/started";
	my $stopped_file = $election_dir."/stopped";

    my (%edata, %vdata);
    tie %edata, "DB_File", $election_data, O_RDONLY, 0777, $DB_HASH;
    tie %vdata, "DB_File", $vote_data, O_RDONLY, 0666, $DB_HASH;

    my $name = decode('utf-8', fixUTF($edata{'name'} || 'undefined'));
    my $title = decode('utf-8', fixUTF($edata{'title'} || 'no title'));

    # $title = HTML::Entities::encode_entities($title);
    my $email_addr = $edata{'email_addr'} || '(no addr)';

    my $public = (defined($edata{'public'}) && $edata{'public'} eq 'yes') ? "Public" : "Private";
    if (defined($edata{'publicize'}) && $edata{'publicize'} eq 'yes') { $public .= '+' }
    if ($edata{'external_ballots'} && $edata{'external_ballots'} eq 'yes') {
        $public = 'Test';
    }
    my $num_auth = $edata{'num_auth'};
    if (!defined($num_auth)) { $num_auth = '&ndash;'; }
    my $num_votes = $vdata{'num_votes'};
    if (!defined($num_votes)) { $num_votes = '&ndash;'; }
    my $started;
    if (-e $started_file) {
	if (defined($edata{'election_begin'})) {
	    $started = '<small>'.localtime($edata{'election_begin'}).'</small>';
	} else {
	    $started = "Yes";
	}
    } else {
	$started = "No";
    }
    my $stopped = (-e $stopped_file) ? "Yes" : "No";
    my $auth_key = (defined($edata{'hash_authorization_key'})) ? "Yes" : "No";
    my $st = stat($election_dir."/vote_data");
    if (!defined($st)) {
	$st = stat($election_dir."/vote_log");
    }
    if (!defined($st)) {
	$st = stat($election_dir."/stopped");
    }
    if (!defined($st)) {
	$st = stat($election_dir);
    }
    my $last_update = 'N/A';
    my $mtime;
    if (defined($st)) {
	$mtime = $st->mtime;
	$last_update = localtime($mtime);
    }
    if (defined($title)) {
	$title = span("\"$title\"");
    } else {
	$title = span('(no title)');
    }

    push @entries,
     [($mtime, $file, $title, $name, $email_addr, $public,
       $num_auth, $num_votes, $started, $stopped, $auth_key, $last_update)];

    untie %edata;
    untie %vdata;
}

our $compares = '';

@entries = sort { $b->[0] <=> $a->[0] } @entries;

my @rows = ();
push @rows, th(['Title', 'Supervisor', 'Type', '# Auth',
                'Votes', 'Start', 'Stopped',
                'Last update', 'Delete']);

foreach my $entry (@entries) {
    (my $mtime, my $file, my $title, my $name, my $email_addr, my $public,
     my $num_auth, my $num_votes, my $started, my $stopped, my $auth_key,
     my $last_update)
	= @{$entry};
    if ($public ne 'Test') {
        if ($num_auth ne '&ndash;') {
	    $total_auth += $num_auth;
	}
        if ($num_votes ne '&ndash;') {
	    $total_users += $num_votes;
	}
    }
    push @rows, Tr(td([a({-href=>"$civs_bin_path/results@PERLEXT@?id=$file".
			         '&admin_key='.uri_escape('@ADMIN_KEY@'),
			  -target=>"_blank"},
	small($title)),
	"$name (" . a({-href=>"mailto:$email_addr"},$email_addr) . ")",
	$public,
	$num_auth,
	$num_votes,
	$started,
	$stopped,
	small($last_update),
	a({-href=>'delete_election@PERLEXT@?id='.$file.'&key='.uri_escape('@ADMIN_KEY@'),
	   -onClick => "return confirm('Are you sure you want to permanently delete this?"},"Delete"),
	]));
}

print p("Number of polls: $num_polls, total votes cast: $total_users, total authorized: $total_auth"), $cr;

# print out table explicitly to work around apparent bug in CGI::table()
#
print '<table class="status">', $cr;
foreach my $row (@rows) {
    print $row, $cr;
}
print '</table>', $cr;

print end_html();
