#find irclogs -type f -execdir perl -i.orig rewrite-logs.pl {} +

# Rewrite irssi's log files to have all lines in the same (timestamp) format

use strict;
use warnings;
use POSIX qw/strftime/;
use constant FMT => "%s [%m/%d/%y %H:%M:%S]";

$ENV{TZ} = 'America/Chicago';

my %months = reverse builtin::indexed qw/Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec/;

#strftime(fmt, sec, min, hour, mday, mon, year)
# all 0-based except mday (1+) and year = real_year-1900.

my ($sm, $sd, $sy);
while (<>) {
	chomp;
	if (/^--- (?:Log opened|Day changed) \w\w\w (?<b>\w\w\w) (?<d>\d\d) (?:(?<H>\d\d):\d\d:\d\d )?(?<Y>\d\d\d\d)/) {
		# Timezone changed at:
		# --- Log closed Wed May 17 20:23:54 2023
		# --- Log opened Wed May 17 19:24:29 2023
		if ($+{Y} eq '2023' && (($+{d} >= 17 && $months{$+{b}} == 4 && defined $+{H} && $+{H} >= 19) || $months{$+{b}} > 4)) {
			$ENV{TZ} = 'America/Denver';
		}

		$sm = $months{$+{b}};
		$sd = $+{d};
		$sy = $+{Y}-1900; # year = %Y - 1900

	} elsif (/^--- Log closed/) { # ignore

	} elsif ($sd && s/^(?<H>\d\d):(?<M>\d\d) //) { # starts with HH:MM
		my $newts = strftime(FMT, 0, $+{M}, $+{H}, $sd, $sm, $sy);
		$_ = "$newts$_";

	} elsif (s@^\[(?<m>\d\d)/(?<d>\d\d)/(?<y>\d\d) (?<H>\d\d):(?<M>\d\d):(?<S>\d\d)\]@@) { # starts with [mm/dd/yy HH:MM:SS]
		my $newts = strftime(FMT, $+{S}, $+{M}, $+{H}, $+{d}, $+{m}-1, (100+$+{y})); # year = 2000 + %y - 1900
		$_ = "$newts$_";

	} elsif (/^1\d{9} \[/) { # starts with unixts
		next; # leave it alone

	} elsif (/^--- /) {
		print STDERR "Unknown --- line: $ARGV:$. $_\n";
	} elsif ($sd) {
		print STDERR "Unknown other line: $ARGV:$. $_\n";
	} else {
		print STDERR "No date for line: $sm $sd $sy $ARGV:$. $_\n";
	}

} continue {
	print "$_\n";
	if (eof) { # if we're about to move on to another file
		$ENV{TZ} = 'America/Chicago'; # reset the timezone for the start of next file (it'll get switched back to Denver again as appropriate)
		close ARGV;
		undef $sm;
		undef $sd;
		undef $sy;
	}
}
