#!/usr/local/bin/perl

###############################################################################
#
# genStats.pl - Generate new stats database, removing old one
#
# AUTHOR:	Shawn Stepper, wiTHinc Inc.
# AUTHOR:	George Toye, wiTHinc Inc.
# DATE:		$Date: 2001/07/16 20:35:05 $ (last modified)
# COPYRIGHT:	1998, 1999, 2000, 2001 wiTHinc Inc. All Rights Reserved.
#
###############################################################################

require "F_Init.pl";

# Get the file name
if (@ARGV[0] eq "") {
	print "usage: $0 class\n";
}

$Class = @ARGV[0];

&lookupClass;

$ad{"_Total"}[0] = 0;

################# Read in all data from new.db, and generate big stats array
$dbfile = "$C_rootpath/$DIR_CLASSFORUM/$DBFILE_FALL";
if (! -e $dbfile) {
	$dbfile = "$C_rootpath/$DIR_CLASSFORUM/$DBFILE_FNEW";
}
foreach (`$prtDB $dbfile -tbtree -a -q`) {
	($key, $value) = split(/\t/, $_);
	$value = &UnEscape($value);
	chomp($value);
	@value = split(/\t/, $value);
	if ($key =~ /\./) {
		($key, $junk) = split(/\./, $key);
	}
	
	# Update stats arrays
	
	# Get the date, in stats format
	($sec, $min, $hr, $day, $mon, $yr, $dow, $doy, $dls) = localtime($key);
	$mon += 1;
	if ($yr >= 100) {
		$yr -= 100;
	}
	$date = sprintf("%02d.%02d.%02d", $mon, $day, $yr);
	
	# update the count for that date
	if ($ad{$date}[0] eq "") {
		$ad{$date}[0] = 1;
	} else {
		$ad{$date}[0] += 1;
	}
	
	# Update the total
	$ad{"_Total"}[0] += 1;
	
	# Now handle the user
	if ($ad{@value[3]}[0] eq "") {
		# New entry
		
		# Total Posts
		$ad{@value[3]}[0] = 1;
		
		if (@value[0] =~ /\./) {
			# Reply
			$ad{@value[3]}[1] = 0;
			$ad{@value[3]}[2] = 1;
		} else {
			# Original Post
			$ad{@value[3]}[1] = 1;
			$ad{@value[3]}[2] = 0;
		}
		# Last Post Date (seconds)
		$ad{@value[3]}[3] = $key;
		# Posts on date last posted
		$ad{@value[3]}[4] = 1;
		# Last post date (mm.dd.yy)
		$ad{@value[3]}[5] = $date;
	} else {
		# Add to existing
		# Total Posts
		$ad{@value[3]}[0] += 1;
		
		if (@value[0] =~ /\./) {
			# Reply
			$ad{@value[3]}[2] += 1;
		} else {
			# Original Post
			$ad{@value[3]}[1] += 1;
		}
		# Last Post Date (seconds)
		$ad{@value[3]}[3] = $key;
		# Posts on date last posted
		if ($date eq $ad{@value[3]}[5]) {
			$ad{@value[3]}[4] += 1;
		} else {
			$ad{@value[3]}[4] = 1;
		}
		# Last post date (mm.dd.yy)
		$ad{@value[3]}[5] = $date;
	}
}

################# Generate stats.db
$dbf = "$C_rootpath/$DIR_CLASSFORUM/$DBFILE_STATS";

# Delete existing stats
rename($dbf, $dbf . ".bak");

foreach $key (keys %ad) {
	$value = join("\\t", @{ $ad{$key} });
	@retval = `$setDB $dbf -tbtree -q -k \"$key\" -d \"$value\"`;
	$status = &dbErrorCheck($?, @retval[0]);
	if ($status) {
		print "$status: Couldn't Update Stats DB ($dbf) for $key.\n";
	}
}

chmod(0666, $dbf);
