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

use FindBin '$RealBin';
use lib "$RealBin/lib";

use Vnlog::Util qw(parse_options read_and_preparse_input ensure_all_legends_equivalent reconstruct_substituted_command);


my @specs = ( "vnl-tool=s",
              "help" );


my ($filenames,$options) = parse_options(\@ARGV, \@specs, 0, <<EOF);
  $0 < pipe

This wraps the 'tac' utility: a tool that reverse the order of lines in the
streaming input. Here we preserve the vnlog legend, and reverse the order of the
data. None of the 'tac' options are supported, since they don't make sense in a
vnlog context. We support one vnl-tac-specific option:

  --vnl-tool tool
       Specifies the path to the tool we're wrapping. By default we wrap 'tac',
       so most people can omit this
EOF
$options->{'vnl-tool'} //= 'tac';

my $inputs = read_and_preparse_input($filenames);


ensure_all_legends_equivalent($inputs);

say "# " . join(' ', @{$inputs->[0]{keys}});

my $ARGV_new = reconstruct_substituted_command($inputs, $options, [], \@specs);

exec $options->{'vnl-tool'}, @$ARGV_new;



__END__

=head1 NAME

vnl-tac - concatenate and print vnlog data in reverse

=head1 SYNOPSIS

 $ cat tst.vnl
 # time temperature
 1.0 29.5
 2.0 30.4
 3.5 28.3
 6.0 22.1


 $ vnl-tac tst.vnl
 # time temperature
 6.0 22.1
 3.5 28.3
 2.0 30.4
 1.0 29.5

=head1 DESCRIPTION

  Usage: vnl-tac < input.vnl
         vnl-tac input.vnl

This tool runs C<tac> on given vnlog streams. C<vnl-tac> is a wrapper around the
GNU coreutils C<tac> tool. The commandline options of C<tac> don't make sense in
the context of vnlog, so only one vnlog-specific option is supported:

=over

=item *

By default we call the C<tac> tool to do the actual work. If the underlying tool
has a different name or lives in an odd path, this can be specified by passing
C<--vnl-tool TOOL>

=back

See the C<tac> manpage for detailed documentation.

=head1 COMPATIBILITY

I use GNU/Linux-based systems exclusively, but everything has been tested
functional on FreeBSD and OSX in addition to Debian, Ubuntu and CentOS. I can
imagine there's something I missed when testing on non-Linux systems, so please
let me know if you find any issues.

=head1 SEE ALSO

L<tac(1)>

=head1 REPOSITORY

https://github.com/dkogan/vnlog/

=head1 AUTHOR

Dima Kogan C<< <dima@secretsauce.net> >>

=head1 LICENSE AND COPYRIGHT

Copyright 2018 Dima Kogan C<< <dima@secretsauce.net> >>

This library is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the Free
Software Foundation; either version 2.1 of the License, or (at your option) any
later version.

=cut
