#!/usr/bin/perl

=head1 NAME

syslog2iso8601 - Octopussy program to convert 'syslog format' logs to 'iso8601' logs

=head1 SYNOPSIS

syslog2iso8601 --device <device> --service <service> 

=head1 DESCRIPTION

=cut

use strict;
use warnings;
use Readonly;

use Getopt::Long;

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

use AAT::Utils qw( ARRAY );
use Octopussy;
use Octopussy::Logs;

Readonly my $PROG_NAME    => 'syslog2iso8601';
Readonly my $PROG_VERSION => Octopussy::Version();

my $help;
my ($opt_device, $opt_service, $opt_timezone) = (undef, undef, undef);

=head1 FUNCTIONS

=head2 Help()

Prints Help

=cut

sub Help
{
    my $help_str = <<"EOF";

$PROG_NAME (version $PROG_VERSION)

 Usage: $PROG_NAME --device <device> --service <service> --timezone <+/-HH:MM>

EOF

    print $help_str;
    if (!defined $opt_device)
    {
        print ' ' . Octopussy::Device::String_List(undef) . "\n";
    }
    elsif (!defined $opt_service)
    {
        print ' '
            . Octopussy::Device::String_Services(ARRAY($opt_device)) . "\n";
    }
    print "\n";

    exit;
}

#
# MAIN
#

my $status = GetOptions(
    'h'         => \$help,
    'help'      => \$help,
    'device=s'  => \$opt_device,
    'service=s' => \$opt_service,
    'timezone=s' => \$opt_timezone,
);

Help()
    if ((!$status)
    || ($help)
    || (!defined $opt_device)
    || (!defined $opt_service)
    || (!defined $opt_timezone));

my ($files, $total) =
    Octopussy::Logs::Get_TimePeriod_Files($opt_device, $opt_service, '197001010000', '202001010000');

my $strp = new DateTime::Format::Strptime(pattern => '%Y %h %e %T');

foreach my $min (sort keys %{$files})
{
    my @logs = ();
    foreach my $f (@{$files->{$min}})
    {
    	if ($f =~ /\/(\d{4})\/\d{2}\/\d{2}\/msg_/)
    	{
            my $year = $1;
			my $cat = ($f =~ /.+\.gz$/ ? 'zcat' : 'cat');
            if (defined open my $FILE, '-|', "$cat \"$f\"")
            {
                while (<$FILE>)
                { 
            	   if ($_ =~ /^(\w{3}) \s?(\d{1,2}) (\d\d:\d\d:\d\d) (.*)$/)
            	   {
            	       my $dt = $strp->parse_datetime("$year $1 $2 $3");
            	       my $str = sprintf("%sT%s.000000%s %s", $dt->ymd('-'), $dt->hms(':'), $opt_timezone, $4);  	
            	       push @logs, $str;
            	   }
                }
                close $FILE;
                if (defined open my $TMPFILE, '|-', "gzip >> ${f}.tmp")
                {
                    foreach my $log (@logs) 
                        { print {$TMPFILE} "$log\n"; }
                    close $TMPFILE;
                    rename "${f}.tmp", $f   if (scalar @logs);
                    @logs = ();
                }
            }
        }
    }
}

=head1 AUTHOR

Sebastien Thebert <octo.devel@gmail.com>

=cut

1;
