#!/usr/bin/perl
#
# Produce user statistics from us_log file
#
# Last Change: DL6RAI: Thu Jul 13 20:50:47 GMT 2000

use Time::Local;

$db_name = "clx_db";
$home = (getpwnam('clx_us'))[7];

$psql = "psql $db_name -qtc";
if ($#ARGV == -1) { 
	$where = ""; 
} elsif ($#ARGV == 0) {
	$ARGV[0] =~ s/-.*//;
	$where = sprintf("WHERE us_call~'%s'",$ARGV[0]);
} else {
	shift; # ignore first argument, because that's my callsign
	$ARGV[0] =~ s/-.*//;

	# Shortcut for all link partners
	if ($ARGV[0] =~ /links/i) {
		shift;
		open(IN,"$home/config/cluster_par");
		while(<IN>) {
			chop;
			if (/^section:/i) { 
				# put callsigns into list
				s/-[0-9]+//;
				push(@ARGV,(split)[1]); 
			}
		}
		close(IN);
	}

	$where = sprintf("WHERE us_call~'%s'",$ARGV[0]);
	shift;
	while (@ARGV) {
		$where .= sprintf(" OR us_call~'%s'",$ARGV[0]);
		shift;
	}
}


$qry = "SELECT us_call,log_act,log_time FROM us_log $where ORDER BY log_time";
# print "Q: $qry\n";
$cmd = $psql . " \"" . $qry . "\"" ;

sub conv_time {
%month = ("Jan", 1,"Feb", 2,"Mar", 3,
	  "Apr", 4,"May", 5,"Jun", 6,
	  "Jul", 7,"Aug", 8,"Sep", 9,
	  "Oct",10,"Nov",11,"Dec",12);

	($lit_mon,$mday,$hour,$min,$sec,$year) = 
		(split(/[ :]/,$log_time))[1..6];
	$mon = $month{$lit_mon};
	return timegm($sec,$min,$hour,$mday,$mon-1,$year);
}

open(LOG,"$cmd |");
while (<LOG>) {
	chop;
        $c++;
        ($us_call,$log_act,$log_time) = (split(/\|/));
	$t = conv_time($log_time);

	# First log entry = start time
	if (! defined($start_time) ) {
		$start_time = $log_time;
		$now = time;
		$total_seconds = $now - &conv_time($start_time);
	}

	# If it's a Connect
	if ($log_act == 1) {
		$conn{$us_call} = $t;
		$connects{$us_call}++;
	# or a disconnect
	} elsif ($log_act == 0) {
		next if ( ! defined($conn{$us_call}));
		$disconn{$us_call} = $t;
		$d = $disconn{$us_call} - $conn{$us_call};

		$total{$us_call} += $d;

		undef($conn{$us_call});
		undef($disconn{$us_call});
	}
}
close(LOG);

# Sum up seconds of stations that are currently connected
foreach $i (keys %conn) {
	if ( $conn{$i} > 0 ) {
		$d = $now - $conn{$i};
		$total{$i} += $d;
		undef($conn{$i});
		undef($disconn{$i});
	}
}

if (defined($start_time) ) {
	print "CLX Connect Time since $start_time\n\n";
	print "Call       Total Time       Connects    avg. Duration  Connects/day\n";
	foreach $i (sort keys %total) {
		$pc = $total{$i}/$total_seconds*100.0 if ($total{$i} != 0);
		printf("%-8s  %5.1f h %5.1f%%      %4d       %4d min        %4d\n",
			$i,$total{$i}/3600,$pc,$connects{$i},
			$total{$i}/$connects{$i}/60,
			$connects{$i}/($total_seconds/3600/24));
	}
} else {
	print "No log entries found.\n";
}
