#!/usr/bin/perl
#$Id: synthing_audit_parser.pl,v b79e1d26f5cd 2017/02/05 15:55:47 grin $
#
# summarizes synthing audit trails
#
#(c)Peter Gervai, 2017
# cc_by-sa-4.0 / GPLv3+
#
##
## usage: synthing_audit_parser.pl ~/.config/syncthing/audit-20170131-235152.log
##

use JSON;
use IO::File;
use strict;
use warnings;

# 0: process log and exit; 1: follow tail forever
my $forever_mode = 1;

binmode(STDOUT, ":utf8");

my $json = JSON->new;

my $f = new IO::File "< " . (shift)  or die "cannot open file";
$f->binmode(":utf8");

my %dev;	# readable names of the nodes
while( 1 ) {
	while( <$f> ) {
	    my @obj = $json->incr_parse( $_ );
	    
	    foreach my $o (@obj) {
	        if( $o->{type} eq "DeviceConnected" ) {
			# register device
			$dev{ substr( $o->{'data'}->{'id'}, 0, 7 ) } = $o->{'data'}->{'deviceName'};
		
	        } elsif( $o->{type} eq "Starting" ) {
			# register our own device
			$dev{ substr( $o->{'data'}->{'myID'}, 0, 7 ) } = 'Me';
			
		} elsif( $o->{type} =~ /ChangeDetected$/ ) {
			my $devname = $dev{ $o->{'data'}->{'modifiedBy'} } || "?";
			printf( "%-35s; %22s; %10s; %15s; %15s; %7s; %5s; %s\n", @{$o}{'time','type'}, 
				@{$o->{'data'}}{'action','folderID'}, 
				$devname, 
				@{$o->{'data'}}{'modifiedBy','type','path'}  );
		}
	    }
	}
	
	exit(0) unless $forever_mode;
	
	print STDERR "--" . scalar(localtime) . " / waiting--\r";
	sleep 1;
	$f->seek(0,1);
}
