#!/usr/bin/perl -w

#
# rssac_yaml_to_fsdb
# $Id$
#
# Copyright (C) 2020 University of Southern California.
# All rights reserved.                                            
#                                                                
# Redistribution and use in source and binary forms are permitted
# provided that the above copyright notice and this paragraph are
# duplicated in all such forms and that any documentation, advertising
# materials, and other materials related to such distribution and use
# acknowledge that the software was developed by the University of
# Southern California, Information Sciences Institute.  The name of the
# University may not be used to endorse or promote products derived from
# this software without specific prior written permission.
# 
# THIS SOFTWARE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED
# WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
# 



=head1 NAME

rssac_yaml_to_fsdb - read RSSAC YAML and output fsdb

=head1 SYNOPSIS

rssac_yaml_to_fsdb  2020/05/traffic-volume/*.yaml

=head1 DESCRIPTION

Reads the YAML, outputs the Fsdb.

=head1 OPTIONS

=over

=item B<-d>

Enable debugging output.

=item B<-v>

Enable verbose output.

=item B<--help>

Show help.

=item B<--man>

Show full manual.

=back

=cut

use strict;
use Pod::Usage;
use Getopt::Long;
use YAML::Tiny;
use Fsdb::IO::Writer;

Getopt::Long::Configure ("bundling");
pod2usage(2) if ($#ARGV >= 0 && $ARGV[0] eq '-?');
#my(@orig_argv) = @ARGV;
my($prog) = $0;
my $debug = undef;
my $verbose = undef;
&GetOptions(
 	'help|?' => sub { pod2usage(1); },
	'man' => sub { pod2usage(-verbose => 2); },
	'd|debug+' => \$debug,   
        'v|verbose+' => \$verbose) or pod2usage(2);
pod2usage("$prog: no files given.\n") if ($#ARGV < 0);

my $out = undef;

sub do_file {
    my($filename) = @_;

    my $yaml = YAML::Tiny->read($filename);

    my $service = $yaml->[0]{'service'} // 'X';
    my $date = $yaml->[0]{'start-period'} // 'xxxx-xx-xx';
    $date =~ s/T[\d:]+Z?$//;
    my $short_service = $service;  $short_service =~ s/\..*$//;
    if (!defined($out)) {
        my @fields = sort grep(/^dns-/, keys(%{$yaml->[0]}));
        foreach (0..$#fields) {
            $fields[$_] =~ s/-/_/g;
        };
        unshift(@fields, 'date', 'service');
        $out = new Fsdb::IO::Writer (-file => '-', -fscode => 't', -cols => \@fields);
        die "error making output: " . $out->error if ($out->error);
    };
    my(@r) = ($date, $short_service);
    foreach (sort grep(/^dns-/, keys(%{$yaml->[0]}))) {
        push(@r, $yaml->[0]{$_});
    };
    $out->write_row_from_aref(\@r);
}

foreach (@ARGV) {
    do_file($_);
};

exit 0;

