#! /usr/bin/perl
# ex:ts=8 sw=4:
# $OpenBSD: dpb-replay,v 1.3 2013/10/15 16:07:21 espie Exp $
#
# Copyright (c) 2013 Marc Espie <espie@openbsd.org>
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
use strict;
use warnings;
use FindBin;

my $ports1;
BEGIN {
	$ports1 = $ENV{PORTSDIR} || '/usr/ports';
}
use lib ("$ports1/infrastructure/lib", "$FindBin::Bin/../lib");
use DPB::MiniCurses;
package Term;
our @ISA = qw(DPB::MiniCurses);

sub new
{
	my ($class, $opt_c) = @_;
	my $self = bless {}, $class;
	$self->create_terminal({color=>$opt_c});
	$SIG{'WINCH'} = sub {
		$self->handle_window;
	};
	return $self;
}

package main;
use Time::HiRes (qw(time sleep));
use OpenBSD::Getopt;


our ($opt_s, $opt_c);
getopts('s:c');
my $file = shift;
my $speedup = $opt_s // 10;
$speedup += 0.0;
my $term = Term->new($opt_c);

open(my $fh, '<', $file);

my $start_ts;
my $start_time = time();
my $msg = '';
while(<$fh>) {
	if (m/^\@\@\@(\d+)$/) {
		chomp;
		my $ts = int($1);
		$start_ts //= $ts;

		my $now = time();
		my $sleep = ($ts-$start_ts)/$speedup - ($now - $start_time);
		if ($sleep > 0) {
			sleep($sleep);
		}
		my $method = $term->{write};
		$term->$method($msg);
		$term->{msg} = $msg;
		$msg = '';
	} else {
		$msg .= $_;
	}
}
close($fh);
