#! /usr/bin/env perl
use strict;
use warnings;
use autodie;

if (@ARGV != 2) { die "Usage: shrinklog.pl size logfile\n" }
my $keep = $ARGV[0];
my $filename = $ARGV[1];
my $length = (stat($filename))[7];
exit 0 if ($keep >= $length);

open my $file, '+<', $filename; # RW
# Start position to look for EOL
seek $file, ($length - $keep), 0;
# Read one line to align on next CR
my $line = <$file>;
# Now copy end at 0 position through 16k buffer
my $begin = tell $file;
my $from = $begin;
my $to = 0;
my $buff;
while (read($file, $buff, 16 * 2 ** 10)) {
    # Keep position for next read
    $from = tell $file;
    # Set position for buffer copy
    seek $file, $to, 0;
    # Copy buffer 
    print $file $buff;
    # Keep position for next copy
    $to = tell $file;
    # Set position back for read
    seek $file, $from, 0;
}

# Truncate file
truncate $file, ($length - $begin);
close $file;
