#!/usr/bin/perl
use strict;
use Fcntl qw(:DEFAULT :flock);
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 $time = time();
my %config = get_config();
my $log_path = defined $config{'userland_event_dir'} ? $config{'userland_event_dir'} : "/var/log/datacycle/";
my $debug = 0;

if ( $#ARGV < 2 || $ARGV[0] ne "-u" || $ARGV[1] !~ /^\w+$/ || !$ARGV[2] ) {
    print "\nUsage: $0 -u USER_NAME -[r|a=FROM_TIMESTAMP:TO_TIMESTAMP]\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 77;
}
if ( $option eq "-r" ) {
    my $uid_salt = crypt($uid,sprintf("%x", $uid));
    if ( $uid_salt ne $ARGV[3]) {
        print "Permission denied\n";
        exit 77;
    }
    my $cache;
    process_log($log_path,$cache);
    if (defined $config{'cluster_userland_event_dir'} ) {
        while(<$config{'cluster_userland_event_dir'}/*>) {
            my $dir = $_;
            next if (! -d $dir);
            process_log($dir,$cache);
        }
    }
    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})$/ ) {
    #I'm pretty sure noone usese this option anymore
    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";
}



sub process_log {
    my $path = shift;
    my $cache = shift;
    my $wildcard_cache;
    my $current_events = "$path/user_logs/$uid";
    my $archive_events = "$path/archives/$uid.$time";
    clean_archives($path);

    print "Processing logs at $current_events\n" if $debug;
    if ( ! -f $current_events ) {
        print "User file event data not found at $current_events.\n" if $debug;
        return;
    }

    my $lock = new File::Flock $current_events;
    move($current_events,$archive_events);
    signal_daemon();
    $lock->lock_rename($archive_events);
    open(FILE,$archive_events);
    while(<FILE>) {
        chomp;
        if ( /^(\d{10}):\d+:(\d+):\d+:(.*)$/ ) {
            my $file = $3;
            if ($2 == 1 || $2 == 2 || ($2 == 6 && -d $file) || $2 == 7)  { # Folder is renamed, removed, or made
                $wildcard_cache->{$file} = 1;
            } else {
                $cache->{$file} = 1;
            }
        }
    }
    close(FILE);
    # Remove any nested wildcard directories
    my @dirs = sort { ($a =~ tr|/||) <=> ($b =~ tr|/||) || $a cmp $b } keys %$wildcard_cache;
    my @wildcards;


    my %wildcard_tree;
    my @wildcards;

    DIR: foreach my $dir (@dirs) {
        my @parts = split m|/|, $dir;
        my $node = \%wildcard_tree;
        for my $part (@parts) {
            last DIR if exists $node->{'*'};  # A parent directory is already a wildcard
            $node = ($node->{$part} //= {});
        }
        $node->{'*'} = 1;  # Mark this directory as a wildcard
        push @wildcards, $dir;
        print "$dir/***\n";
    }

    # Print any files not in a wildcard directory
    while (my ($file) = each %$cache) {
        my @parts = split m|/|, $file;
        my $node = \%wildcard_tree;
        my $covered = 0;

        for my $part (@parts) {
            if (exists $node->{'*'}) {
                $covered = 1;
                last;
            }
            last unless exists $node->{$part};
            $node = $node->{$part};
        }

        print "$file\n" unless $covered;
    }
    system("gzip $archive_events >/dev/null 2>/dev/null");
    $lock->unlock();
}

sub signal_daemon {
    my $pid_file = '/var/run/datacycle-ebpf.pid';
    if ( -f $pid_file ) {
        open(my $fh, '<', $pid_file);
        my $pid = <$fh>;
        close($fh);
        if ( $pid && $pid =~ /^\d+$/ ) {
            kill('HUP', $pid);
        }
    }
}

sub clean_archives {
    my $path = shift;
    if ( -f "$path/archives.clean_time" && stat("$path/archives.clean_time")->mtime > time()-86400 ) {
        print "Archives have been cleaned less than 24 hours ago.\n" if $debug;
        return;
    }
    open(WRITE,'>', "$path/archives.clean_time");
    close(WRITE);

    return if (! -d "$path/archives");
    while(<$path/archives/*gz>) {
        my $file = $_;
        next if ( ! -f $file );
        if ( $file =~ m|/\d+\.(\d{10})\.gz$| && $1 < time()-604800*2) {
            print "$file older than 14 days... unlinking\n" if $debug;
            unlink($file);
        }
    }
    while(<$path/user_logs/*>) {
        my $file = $_;
        next if ( ! -f $file );
        if ( $file =~ m|/\d+$| && stat($file)->mtime < time()-604800*4) {
            print "$file older than 1 month... unlinking\n" if $debug;
            unlink($file);
        }
    }
}

sub get_config {
     my %config;
    if ( ! -f '/etc/datacycle/datacycle.conf' ) {
        die "[!] Config file [/etc/datacycle/datacycle.conf] not found!\n";
    }
    open(my $DAT, '<', '/etc/datacycle/datacycle.conf');
        while(<$DAT>) {
            chomp();
            if ( /^(.*)?=(.*)?$/ ) {
                $config{$1} = $2;
            }
        }
    close($DAT);
    return %config;
}
