#!/usr/local/bin/perl

# 
# set tabstop=4 of course
#

use Date::Manip;
use Getopt::Std;

our($opt_t,$opt_d,$opt_e,$opt_h);
getopts ('t:deh');
# t = throughput
# d = disk space
# e = email results
# h = help

syntax() if($opt_h);
syntax() unless($opt_t || $opt_d);

if($opt_t){
	if($opt_t eq "monthly"){
		$period = ParseDate('last month');
	}elsif($opt_t eq "weekly"){
		$period = ParseDate('last week');
	}elsif($opt_t eq "daily"){
		$period = ParseDate('24 hours ago');
	}else{
		print "syntax error\n";
		syntax();
	}
	$period =~ /(^\d{8})(\d{2}:\d{2}:\d{2})/; $days=$1; $time=$2;
}

opendir(D, "/home/hostedsites/") || die "cannot opendir: $!\n";
 @subdirs = grep {/^www\./} readdir D;
closedir D;

foreach my $subdir (@subdirs){
	my $total=0;
	if($opt_t){
		opendir(S, "/home/hostedsites/$subdir/logs/") || die "cannot opendir logs: $!\n";
		foreach my $file (grep {!/^\./} readdir S){
			if($file >= $days){
				open(F, "/home/hostedsites/$subdir/logs/$file") || die "cannot open log: $!\n";
				while(<F>){
					if(($file eq $days) && /\[.+:(\d{2}:\d{2}:\d{2})/){
						$logtime=$1;
						$flag = Date_Cmp($time,$logtime);
						if($flag > 0){
							next;
						}
					}
					$size = (split /\s+/)[9]; # bytes of served file (not incl overhead)
					if($size > 0){
						$total += $size;
					}else{
						$total += 10; # account for overhead, etc
					}
				}
				close F;
			}
		}
		closedir S;
		$bbits = ($total*8);
		if($bbits >= 1073741824){
			$throughput = sprintf("%.2f",($bbits/1073741824)) . " gigabits";
		}elsif($bbits >= 1048576){
			$throughput = sprintf("%.2f",($bbits/1048576)) . " megabits";
		}elsif($bbits >= 1024){
			$throughput = sprintf("%.2f",($bbits/1024)) . " kilobits";
		}else{
			$throughput = $bbits . " bits";
		}

	}
	if($opt_d){
		($skbytes)=split(/\s+/, `du -s -k /home/hostedsites/$subdir/`);
		if($skbytes >= 1048576){
			$storage = sprintf("%.2f",($skbytes/1048576)) . " GigaBytes";
		}elsif($skbytes >= 1024){
			$storage = sprintf("%.2f",($skbytes/1024)) . " MegaBytes";
		}else{
			$storage = $skbytes . " KiloBytes";
		}
	}

	if(defined($opt_d) && defined($opt_t)){
		push @array, "$subdir,$throughput,$storage";
	}elsif(defined($opt_d)){
		push @array, "$subdir,$storage";
	}elsif(defined($opt_t)){
		push @array, "$subdir,$throughput";
	}else{
		print "syntax error\n";
		syntax();
	}
}

if($opt_e){
	$boundary="asfsdf2asdsdias4fJK";
	open(S, "| /usr/lib/sendmail -t") || die "cannot fork sendmail: $!\n";
	print S "From:  Webserver <webserver\@example>\n",
	        "To: SysOp <foo\@example>\n",
	        "Subject: WebSite Utilizations\n",
	        "Mime-Version: 1.0\n",
	        "Content-Type: multipart/mixed; boundary=\"$boundary\"\n",
	        "Content-Disposition: inline\n",
	        "\n",
	        "--$boundary\n",
	        "Content-Type: text/plain; charset=us-ascii\n",
	        "Content-Disposition: inline\n",
	        "\n",
	        "Enclosed is website-util.csv - double click the attachment to view utilizations in Excel.\n",
		"showing utilization between $period and " . `date "+%Y%m%d %H:%M:%S"`,
	        "\n",
	        "--$boundary\n",
	        "Content-Type: text/plain; charset=us-ascii\n",
	        "Content-Disposition: attachment; filename=\"website-util.csv\"\n",
	        "\n";
		foreach(@array){
			print S "$_\n";
		}
		print S "--$boundary--\n";
	close S;
}else{
	print "showing stats between $period and " . `date "+%Y%m%d %H:%M:%S"`;
	foreach(@array){
		print "$_\n";
	}
}
sub syntax {
	die "syntax: webutil.pl [-t daily|weekly|monthly] [-d] [-e] [-h]\n",
	    "where: -t      calculate throughput over this period (daily, weekly, or monthly)\n",
	    "       -d      calculate disk usage\n",
	    "       -e      email results\n",
	    "       -h      this help screen\n";
}
