#!/usr/bin/perl -w
#
# __copy1__
# __copy2__
#
my $CMD		= $0; $CMD =~ s/.*\///;
my $CMDVER	= "1.0";
my $CMDSTR	= "$CMD v$CMDVER (2019/08)";


my @files;
my $outdir	= "../samba-norm";
my $force = 0;


while (scalar @ARGV) {
	$_ = shift( @ARGV );

	if ($_ eq "-f")		{ $force = 1; next; }
	if ($_ eq "--force")	{ $force = 1; next; }
	if ($_ eq "-d" || $_ eq "--outdir") {
		usage( "--outdir needs an argument" )	if (!@ARGV);
		$outdir = shift( @ARGV );
		next;
	}
	if ($_ eq "--")		{ last; }
	if ($_ =~ /^-/)		{ usage( "unknnown argument '$_'" ); }

	push( @files, $_ );
}
push( @files, @ARGV );

usage( "no files?" )	if (!scalar @files);


if (! -d $outdir) {
	mkdir( $outdir, 0775 );
	printf( STDERR " created dir: $outdir\n" );
}

while (scalar @files) {
	process_file( shift @files );
}

exit( 0 );


sub usage
{
	print( STDERR "
== $CMDSTR == normalize samba logfiles ==

usage: $CMD [options] file(s)

options:
 -f|--force	overwrites normalized files even if the are up-to-date

 --outdir dir	uses 'dir' as output directory instead of '$outdir'
 -d dir

 --		stops arguments parsing\n" );
	print( STDERR "\n** error **\n\n", @_, "\n\n" )	if (scalar @_);
	exit( 1 );
}


sub process_file
{
	my ($IN) = @_;

 	my $outfile = $outdir . "/" . $IN;
 	my $OUT = $outfile . ".tmp";

	my $must_do = 0;
	my $zipped = 0;
	my $date;
	my @fld;

	if (-f $outfile) {
		my @st1 = stat( $IN );
		my @st2 = stat( $outfile );
		if ($st1[9] > $st2[9]) {
			$must_do = 1;
		}
	} else {
		$must_do = 1;
	}

	if (!$must_do) {
 		printf( STDERR " up-to-date $IN\n" );
		next;
	}

 	printf( STDERR " processing $IN ... " );

	if ($IN =~ /\.gz$/) {
		$zipped = 1;
		open( IN, "gzip -d <'$IN' |" )	or die( "can't open 'gzip -d <$IN': $!\n" );
	} else {
		open( IN, "<$IN" )		or die( "can't open '$IN': $!\n" );
	}
	open( OUT, ">$OUT" )	or die( "can't write on '$OUT': $!\n" );

	while (<IN>) {
		chomp();

		if ($_ =~ /^\[/) {
			@fld	= split( / / );
			$date	= $fld[0] . " " . $fld[1];
			$date	=~ s/\[//;
			$date	=~ s/,//;
			$date	=~ s/\..*//;
			next;
		}

    		if ($_ =~ /winreg_create_printer:.*already exists/) {
			next;
		}

		s/^\s+//;

		print( OUT $date, " ", $_, "\n" );
	}

	close( IN );
	close( OUT );

	if ($zipped) {
		printf( STDERR "(zipping) ... " );
		system( "gzip <$OUT >$outfile" )	and die "error on: gzip <$OUT >$outfile: $!\n";
		unlink( $OUT );
	} else {
		rename( $OUT, $outfile );
	}

	system( "touch", "--reference", $IN, $outfile )	and die "error on: touch$!\n";
	printf( STDERR "ok\n" );

	return 0;
}
