#!perl

our $AUTHORITY = 'cpan:PERLANCAR'; # AUTHORITY
our $DATE = '2020-12-12'; # DATE
our $DIST = 'App-SubtitleUtils'; # DIST
our $VERSION = '0.003'; # VERSION

$secs_re = qr/[+-]?\d+(?:\.\d*)?/;
$hms_re = qr/[+-]?\d\d?:\d\d?:\d\d?(?:,\d{1,3})?/;
$hms_re_catch = qr/([+-]?)(\d\d?):(\d\d?):(\d\d?)(?:,(\d{1,3}))?/;
sub hms2secs { local $_=shift; /^$hms_re_catch$/ or return; "${1}1" * ($2*3600+$3*60+$4+$5*0.001) }
sub secs2hms { local $_=shift; /^$secs_re$/ or return "00:00:00,000"; my $ms=1000*($_-int($_)); $_=int($_); my $s=$_%60; $_-=$s; $_/=60; my $m=$_%60; $_-=$m; $_/=60; sprintf "%02d:%02d:%02d,%03d",$_,$m,$s,$ms }

###

$|++;
die "Usage: $0 secs FILE\n" unless @ARGV >= 1;
$_ = shift @ARGV;
if (/^$secs_re$/) {
	$secs = $_;
} elsif (/^$hms_re$/) {
	$secs = hms2secs($_);
} else {
	die "FATAL: Invalid secs `$_'\n";
}

$para = "";
$lines = 1;
while (1) {
	$_ = <>;
	if (/\S/ || $lines <= 2) {
		s/\015//g;
		$para .= $_;
		$lines++;
	} elsif ($para =~ /\S/) {
		($no, $hms1, $hms2, $text) = $para =~ /(\d+)\n($hms_re) ---?> ($hms_re)\n(.*)/s or
			die "FATAL: Invalid entry in line $.: $para\n";
		print $no, "\n",
			secs2hms(hms2secs($hms1)+$secs), " --> ", secs2hms(hms2secs($hms2)+$secs), "\n",
			$text, "\n";
		$para = "";
	} else {
		$lines = 1;
		$para = "";
	}
	last unless $_;
}

# ABSTRACT: Shift the times in .srt by a specified number of seconds
# PODNAME: srtshift

__END__

=pod

=encoding UTF-8

=head1 NAME

srtshift - Shift the times in .srt by a specified number of seconds

=head1 VERSION

This document describes version 0.003 of srtshift (from Perl distribution App-SubtitleUtils), released on 2020-12-12.

=head1 SYNOPSIS

 % srtshift <secs> [FILE] ...

=head1 HISTORY

2003-02-06 - first written

=head1 HOMEPAGE

Please visit the project's homepage at L<https://metacpan.org/release/App-SubtitleUtils>.

=head1 SOURCE

Source repository is at L<https://github.com/perlancar/perl-App-SubtitleUtils>.

=head1 BUGS

Please report any bugs or feature requests on the bugtracker website L<https://github.com/perlancar/perl-App-SubtitleUtils/issues>

When submitting a bug or request, please include a test-file or a
patch to an existing test-file that illustrates the bug or desired
feature.

=head1 AUTHOR

perlancar <perlancar@cpan.org>

=head1 COPYRIGHT AND LICENSE

This software is copyright (c) 2020 by perlancar@cpan.org.

This is free software; you can redistribute it and/or modify it under
the same terms as the Perl 5 programming language system itself.

=cut
