#!/usr/bin/perl -w

use strict;
use vars qw( 
	$DEBUG $BAK_BASE @BAK_VERSIONS %RESULTS @SCRIPT_PATTERNS 
	%CHANGES %SCRIPTS
);
use Cwd 'abs_path';
use JSON;

$DEBUG = 1;

@BAK_VERSIONS = glob qw( /.zfs/snapshot/autosnap* );

@SCRIPT_PATTERNS = ('.php$', '^.htaccess$', '.js$');


%RESULTS = ();
if (@ARGV) {
	chomp(my $site = $ARGV[0]);
	my $real_site = abs_path($site);
	foreach my $bak_vers ( @BAK_VERSIONS ) {
		my $bak_site = $bak_vers . $real_site;
		if ( -e  $bak_vers ) {
			my @bak_stat = stat($bak_vers);
			my $bak_date = $bak_stat[9];
			$RESULTS{'data'}{$bak_date} = ();
			$RESULTS{'data'}{$bak_date}{'files'}   = (); 
			$RESULTS{'data'}{$bak_date}{'added'}   = 0; 
			$RESULTS{'data'}{$bak_date}{'deleted'} = 0; 
			$RESULTS{'data'}{$bak_date}{'changed'} = 0; 
			$RESULTS{'data'}{$bak_date}{'scripts'}     = 0;
			open(DIFF, "diff -qr $real_site $bak_site |") 
				|| die("Could not diff, $!\n");
			while (<DIFF>) {
				if ( m/^Files (.+) and (.+) differ/ ) {
					my $file = substr($1, length($real_site));
					$RESULTS{'data'}{$bak_date}{'files'}{$file} = 'changed';
					$RESULTS{'data'}{$bak_date}{'changed'}++;
					foreach my $script (@SCRIPT_PATTERNS) {
						if ( $file =~ m/$script/ ) {
							$RESULTS{'data'}{$bak_date}{'scripts'}++;
							$SCRIPTS{$file} = 1;
							last;
						}
					}
					$CHANGES{$file} = 1;
				}
				elsif ( m/^Only in (.+): (.+)/ ) {
					if ( substr($1, 0, length($real_site)) eq $real_site) {
						my $file = substr($1, length($real_site)) . '/' . $2;
						$RESULTS{'data'}{$bak_date}{'files'}{$file} = 'added';
						$RESULTS{'data'}{$bak_date}{'added'}++; 
						foreach my $script (@SCRIPT_PATTERNS) {
							if ( $file =~ m/$script/ ) {
								$RESULTS{'data'}{$bak_date}{'scripts'}++;
								$SCRIPTS{$file} = 1;
								last;
							}
						}
						$CHANGES{$file} = 1;
					}
					else {
						my $file = substr($1, length($bak_site)) . '/' . $2;
						$RESULTS{'data'}{$bak_date}{'files'}{$file} = 'deleted';
						$RESULTS{'data'}{$bak_date}{'deleted'}++; 
						foreach my $script (@SCRIPT_PATTERNS) {
							if ( $file =~ m/$script/ ) {
								$RESULTS{'data'}{$bak_date}{'scripts'}++;
								$SCRIPTS{$file} = 1;
								last;
							}
						}
						$CHANGES{$file} = 1;
					}
				}
				else {
					print('# ' . $_);
				}
				
			}
			close(DIFF);
		}
		else {
			print STDERR ($bak_vers . " does not exist\n");
		}
	}
}
else {
	die "Usage: $0 DocumentRoot\n";
}


$RESULTS{'lastrun'} = time();
$RESULTS{'changes'} = scalar(keys %CHANGES);
$RESULTS{'scripts'} = scalar(keys %SCRIPTS);
print(to_json(\%RESULTS, {pretty => 1}) );
