#!/usr/bin/perl

use strict;
use DateTime;
use DateTime::Format::Strptime;

my $timestamp_parser = new DateTime::Format::Strptime(pattern => "%b %d %H:%M:%S.%3N");
my $timestamp_formatter = new DateTime::Format::Strptime(pattern => "%Y-%m-%d %H:%M:%S.%3N");

my $run_ts;
my $fingerprint;
my $poll_ts;
my $answer_ts;
my $resolved_ts;
my $resolution;

print("fingerprint,run_ts,poll_ts,answer_ts,resolved_ts,resolution\n");
while (<>) {
	chomp;
	my ($ts, $level, $line) = ($_ =~ /^(.*) \[(\w+)\] (.*)$/) or die;
	$ts = $timestamp_parser->parse_datetime($ts);
	$ts->set(year => 2023);
	# print("[[[$line]]]\n");
	if ($line =~ /.*running on/) {
		$run_ts = $ts;
		undef($fingerprint);
	} elsif ($line =~ /^new bridge descriptor '\w+' \(\w+\): \$([0-9A-F]+)/) {
		$fingerprint = $1;
	} elsif ($line =~ /^Managed proxy ".*?": offer created$/) {
		!defined($poll_ts) or die "unresolved poll $poll_ts";
		$poll_ts = $ts;
	} elsif ($line =~ /^Managed proxy ".*?": broker rendezvous peer received$/) {
		$answer_ts = $ts;
	} elsif ($line =~ /^Managed proxy ".*?": trying a new proxy: timeout waiting for DataChannel\.OnOpen$/) {
		$resolved_ts = $ts;
		$resolution = "proxy-timeout";
 	} elsif ($line =~ /^Managed proxy ".*?": broker failure timed out waiting for answer!$/) {
 		$resolved_ts = $ts;
 		$resolution = "broker-timeout";
	} elsif ($line =~ /^Managed proxy ".*?": connected$/) {
		$resolved_ts = $ts;
		$resolution = "connected";
	}
	if (defined($resolution)) {
		print(join(",",
			$fingerprint,
			$timestamp_formatter->format_datetime($run_ts),
			$timestamp_formatter->format_datetime($poll_ts),
			defined($answer_ts) ? $timestamp_formatter->format_datetime($answer_ts) : "",
			$timestamp_formatter->format_datetime($resolved_ts),
			$resolution,
		), "\n");
		undef($poll_ts);
		undef($answer_ts);
		undef($resolved_ts);
		undef($resolution);
	}
}
!defined($poll_ts) or die "unresolved poll $poll_ts";
