#!/usr/bin/perl
use strict;
use Fcntl qw(:DEFAULT :flock);
#use Logfile::Rotate;
use File::Flock;
use File::Copy;
use File::stat;

use IO::Compress::Gzip;
use IO::Uncompress::Gunzip;

use Data::Dumper;

my $cache_limit = 50000;
my $log_path = "/var/log/datacycle/";
my $time = time();


if ( $#ARGV < 2 ) {
	print "\nUsage: $0 -u USER_NAME -[r|a=FROM_TIMESTAMP:TO_TIMESTAMP]\n";
	exit;
}

if ( $ARGV[0] ne "-u" || $ARGV[1] !~ /^\w+$/ || !$ARGV[2] ) {
	print "\nPlease use proper usage\n\n";
	exit;
}

my $ppid = getppid();
open(FILE, "/proc/$ppid/cmdline");
my @cmdline = <FILE>;
close(FILE);


my $user = $ARGV[1];
my $uid = getpwnam($user);
my $option = $ARGV[2];

if ( $uid < 1 ) {
	print "\nThe username you provided is invalid\n\n";
	exit;
}

my $current_events = "$log_path/user_logs/$uid";
my $archive_events = "$log_path/archives/$uid.$time";

sub clean_archives {
	if ( -f "$log_path/archives.clean_time" ) {
		if ( stat("$log_path/archives.clean_time")->mtime > time()-86400 ) {
			print "Archives have been cleaned less than 24 hours ago.\n";
			return;
		}
		
	}

	open(WRITE,'>', "$log_path/archives.clean_time");
	close(WRITE);

	if ( ! -d "$log_path/archives" ) {
		return;
	}


	while(<$log_path/archives/*>) {
		my $file = $_;
		if ( ! -f $file ) {
			print "$file isn't a file\n";
			next;
		}
	
		if ( $file !~ /\/\d+\.(\d{10})\.gz$/) {
			print "$file doesn't match regex\n";
			next;
		} else {
			my $file_time = $1;
	
			
			if ( $file_time < time()-604800*2 ) {
				print "$file older than 14 days... unlinking\n";
				unlink($file);
				next;
			}
		}
	
		
	}


	while(<$log_path/user_logs/*>) {
                my $file = $_;
                if ( ! -f $file ) {
                        print "$file isn't a file\n";
                        next;
                }

                if ( $file !~ /\/\d+$/) {
                        print "$file doesn't match regex\n";
                        next;
                } else {
                        my $file_time = $1;


                        if ( $file_time < time()-604800*4 ) {
                                print "$file older than 1 month... unlinking\n";
                                unlink($file);
                                next;
                        }
                }


        }


}


if ( $option eq "-r" ) {
	my $uid_salt = crypt($uid,sprintf("%x", $uid));

	# Remove backup.pl requirement for now
	#if ( $cmdline[0] !~ /backup\.pl/ || $uid_salt ne $ARGV[3]) {
	if ( $uid_salt ne $ARGV[3]) {
		print "Permission denied\n";
		exit 77;
	}


	if ( ! -f $current_events ) {
		print "\nUser file event data doesn't exist.\nEither this user has never written data, or there is a problem\n\n";
		exit;
	}

	clean_archives;

	my $lock = new File::Flock $current_events;
	move($current_events,$archive_events);
	$lock->lock_rename($archive_events);
	my %cache;
	open(FILE,$archive_events);
	while(<FILE>) {
		chomp;
		if ( /^(\d{10}):\d+:\d+:\d+:(.*)$/ ) {
			if ( ! $cache{$2} ) {
				print "$2\n";
				$cache{$2} = 1;
			}
		}
	}
	close(FILE);
	system("gzip $archive_events >/dev/null 2>/dev/null");
	$lock->unlock();
	if ( scalar(keys %cache) >= $cache_limit ) { 
		open(my $DAT, '>>', '/var/log/datacycle/file_change.log');
			print $DAT time() . ' ' . $uid . ' ' . scalar(keys %cache) . "\n";
		close($DAT); 
	}
} elsif ( $option =~ /^\-a=(\d{10}):(\d{10})$/ ) {
	my %path_hash = ();
	my $from_time=$1;
	my $to_time=$2;
	while(<$log_path/archives/*>) {
		if ( /\/$uid\.(\d{10})\.gz$/ ) {
			my $archive_file = $_;
			$path_hash{$1} = $archive_file;
			print "$archive_file\n";
		}
	}

	my $last;
	my $last_used = 0;

	for my $key ( sort {$a<=>$b} keys %path_hash) {
		if ( $key >= $from_time && $key <= $to_time ) {
			if ($last_used == 0) {
				$last_used = 1;
				print "($key)->($path_hash{$key})\n";
				my $z = IO::Uncompress::Gunzip->new( $path_hash{$key} );
				while(<$z>) {
					chomp;
					if ( /^(\d{10}):\d+:\d+:\d+:(.*)$/ ) {
						if ( $key >= $from_time && $key <= $to_time ) {
							print "$2\n";
						}
					}
				}
			}
			print "($key)->($path_hash{$key})\n";
			my $z = IO::Uncompress::Gunzip->new( $path_hash{$key} );
			while(<$z>) {
				chomp;
				if ( /^(\d{10}):\d+:\d+:\d+:(.*)$/ ) {
					if ( $key >= $from_time && $key <= $to_time ) {
						print "$2\n";
					}
				}
			}
		} else {
			$last = $path_hash{$key};
		}

	}
} else {
	print "Incorrect options have been specified..\n";
	print "Please use..\n";
	print "\t-r to rotate the user, and print out changes\n";
	print "\t-a=FROM_TIMESTAMP:TO_TIMESTAMP to view archived events.\n\n";
}

