############################################################################
##      Copyright (C) 2006 Subredu Manuel  <diablo@iasi.roedu.net>.        #
##                                                                         #
## This program is free software; you can redistribute it and/or modify    #
## it under the terms of the GNU General Public License as published by    #
## the Free Software Foundation; either version 2 of the License, or       #
## (at your option) any later version.                                     #
##                                                                         #
## This program is distributed in the hope that it will be useful,         #
## but WITHOUT ANY WARRANTY; without even the implied warranty of          #
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the           #
## GNU General Public License for more details.                            #
##                                                                         #
## You should have received a copy of the GNU General Public License       #
## along with this program; if not, write to the Free Software             #
## Foundation, Inc., 59 Temple Place - Suite 330, Boston,                  #
## MA 02111-1307,USA.                                                      #
############################################################################

package RoPkg::Rsync::LogParser;

use strict;
use warnings;

use Scalar::Util qw(blessed);
use English      qw(-no_match_vars);
use Data::Dumper;
use RoPkg::Exceptions;

use vars qw($VERSION);
$VERSION='0.1';

sub new {
  my ($class, %opt) = @_;
  my $self;
  
  $self = bless { %opt }, $class;

  if (!$self->{type}) {
    Param::Missing->throw('log type not specified');
  }

  if ($self->{type} ne 'server' &&
      $self->{type} ne 'client') {
    Param::Wrong->throw('log type not know to me');
  }

  $self->_create_get_methods();

  return $self;
}

#
# Get/Set the raw rsync log
# 
sub Log {
  my ($self, $raw_log) = @_;

  if ( !blessed($self) ) {
    OutsideClass->throw('Called outside class instance');
  }

  if ( !$raw_log ) {
    return $self->{_raw_log};
  }
  else {
    return ($self->{_raw_log} = $raw_log);
  }
}

#
# Get/Set rsync probes list
#
sub Probes {
  my ($self, @probes) = @_;

  if ( !blessed($self) ) {
    OutsideClass->throw('Called outside class instance');
  }

  if ( !@probes ) {
    if ( $self->{_probes} ) {
      return @{ $self->{_probes} };
    }
    else {
      return 0;
    }
  }
  else {
    push @{ $self->{_probes} }, @probes;
    return scalar(@{ $self->{_probes} });
  }
}

sub _read_log_file {
  my ($self, $filename) = @_;
  my $fh;

  if ( ! -f $filename ) {
    Param::Wrong->throw("$filename is not a file");
  }

  if ( ! open($fh, '<', $filename) ) {
    File::Open->throw("Could not open $filename");
  }

  {
    local $RS;
    $self->{_raw_log} = <$fh>;
  }

  close($fh);

  return scalar($self->{_raw_log});
}

sub _clean {
  my ($self) = @_;

  $self->{_transfered_files} =
  $self->{_real_transfered_files} =
  $self->{_deleted} =
  $self->{_real_deleted} =
  $self->{_speed} =
  $self->{_size} =
  $self->{_transfered_bytes} =
  $self->{_symlinks} =
  $self->{_symlink_targets} =
  $self->{_real_symlinks} =
  $self->{_real_symlink_targets} =
  ();

  return ();
}

###################################
# rsync client log parser - BEGIN #
###################################

sub Parse {
  my ($self, $filename) = @_;
  my $inside = 0;

  if ( !blessed($self) ) {
    OutsideClass->throw('Called outside class instance');
  }

  $self->_clean();

  if ( $filename ) {
    $self->_read_log_file($filename);
  }

  if ( !$self->{_raw_log} ) {
    return 0;
  }

  foreach(split(/[\n\r]/xm, $self->{_raw_log})) {
    my $line = $_;

    next if ( $line =~ m{^\s*$}xm );

    if ( $line =~ m{^receiving \s file .*}xm ) {
      $inside = 1;
      next;
    }

    if ( $line =~ m{^(sent|wrote).*}xm || $line =~ m{^total \s+ size.*}xm ) {
      $self->_parse_report($line);
      next;
    }

    if ( $line =~ m{^deleting.*}xm ) {
      $self->_parse_delete($line);
      next;
    }

    if ( $line =~ m{.* (-|=)> .*}xm ) {
      $self->_parse_symlink($line);
      next;
    }

    next if ( !$inside );
    next if ( $line =~ m{^created \s .*$}xm );

    if ( !$self->_is_probe($line) ) {
      push @{ $self->{_transfered_files} }, $line;
    }

    push @{ $self->{_real_transfered_files} }, $line;
  }

  return 1;
}

sub _parse_delete {
  my ($self, $line) = @_;

  $line =~ s/deleting\s*//xm;

  if ( !$self->_is_probe($line) ) {
    push @{ $self->{_deleted} }, $line;
  }

  push @{ $self->{_real_deleted} }, $line;
  return scalar (@{ $self->{_deleted} });
}

sub _parse_symlink {
  my ($self, $line) = @_;

  my @lines = split(/[\s\-=>]+/xm, $line);
  if ( !$self->_is_probe($lines[0]) && !$self->_is_probe($lines[1]) ) {
    push @{ $self->{_symlinks} }, $lines[0];
    push @{ $self->{_symlink_targets} }, $lines[1];
  }

  push @{ $self->{_real_symlinks} }, $lines[0];
  push @{ $self->{_real_symlink_targets} }, $lines[1];

  return 1;
}

sub _parse_report {
  my ($self, $line) = @_;

  if ( $line =~ m{^(sent|wrote) \s+ (\d+) \s+ bytes \s+
                   (received|read) \s+ (\d+) \s+ bytes \s+
                   ([0-9.]+) \s+ bytes\/sec$}xm ) {
    $self->{_transfered_bytes} = $4;
    $self->{_speed} = $5;
  }
  elsif ( $line =~ m{^total \s+ size \s+ is \s+ (\d+)\s.*$}xm ) {
    $self->{_size} = $1;
  }

  return 1;
}

sub _is_probe {
  my ($self, $pname) = @_;

  foreach(@{ $self->{_probes} }) {
    return 1 if ( $_ eq $pname );
  }

  return 0;
}

###################################
# rsync client log parser -   END #
###################################

#######################
# GET methods - BEGIN #
#######################

sub _get_value {
  my ($self, $pname) = @_;

  if ( !defined($self->{$pname}) ) {
    if ( wantarray ) {
      return ();
    }
    else {
      return 0;
    }
  }

  # if we have a array
  if ( ref($self->{$pname}) eq 'ARRAY' ) {
    return (wantarray ? @{$self->{$pname}} : (scalar @{ $self->{$pname} }));
  }
  else {
    return $self->{$pname};
  }
}

# Here we have to create some wrappers around _get_value.
# Since the code is almost the same for all methods, I
# created the methods dynamically at runtime. Since this
# may not be the best  way to write the methods, is the
# shortest.
sub _create_get_methods {
  my ($self) = @_;

  my $mmaper = {
    'Files'       => '_transfered_files',
    'RealFiles'   => '_real_transfered_files',
    'Deleted'     => '_deleted',
    'RealDeleted' => '_real_deleted',
    'Speed'       => '_speed',
    'Size'        => '_size',
    'TransfData'  => '_transfered_bytes',
  };

  no strict 'refs';
  foreach(keys(%{ $mmaper })) {
    my $pname = $_;
    my $pval  = $mmaper->{$pname};

    next if ( $self->can($pname) );
    *{'RoPkg::Rsync::LogParser::' . $pname} = sub {
                                               my ($self) = @_;

                                               if (!blessed($self)) {
                                                 OutsideClass->throw('Called outside class instance');
                                               }

                                               return $self->_get_value($pval);
    };
  }
  use strict;

  return keys(%{ $mmaper });
}

# Returns a reference to a hash in which the keys are the symlinks,
# and the values are symlinks targets.
sub Symlinks {
  my ($self) = @_;
  my $result = ();
  my $i = 0;

  if ( !blessed($self) ) {
    OutsideClass->throw('Called outside class instance');
  }

  foreach(@{ $self->{_symlinks} }) {
    $result->{$_} = $self->{_symlink_targets}->[$i];
    $i++;
  }

  return $result;
}

# Returns a reference to a hash in which the keys are the symlinks,
# and the values are symlinks targets.
sub RealSymlinks {
  my ($self) = @_;
  my $result = ();
  my $i = 0;

  if ( !blessed($self) ) {
    OutsideClass->throw('Called outside class instance');
  }

  foreach(@{ $self->{_real_symlinks} }) {
    $result->{$_} = $self->{_real_symlink_targets}->[$i];
    $i++;
  }

  return $result;
}


#######################
# GET methods -   END #
#######################

1;

__END__

=head1 NAME

RoPkg::Rsync::LogParser - a rsync log parser class

=head1 SYNOPSIS

 #!/usr/bin/perl
 
 use strict;
 use warning;

 sub main {
   my $lp = new RoPkg::Rsync::LogParser( type => 'client' );

   $lp->Parse('/tmp/debian-log.txt');
 }

 main();

=head1 Short description

RoPkg::Rsync::LogParser is a class used to parse (for the moment)
client side rsync logs. Using this class you can extract the
transfered files, symlinks created, directories, total number
of files, transfered bytes, speed of transfer etc. LogParser
support list filter trough probes (used by many projects to
verify the mirrors). The primary use of this class is inside
Simba, but can be used without problems in any other project
who needs a rsync client log parser.

=head1 METHODS

=head2 new(hash)

Constructor of the class. When creating a new class instance
you must provide the type of log: B<client> or B<server> . For
the moment only the client parsing routines are defined.

=head2 Log($raw_log)

Get/Set the raw rsync log. With no parameters, the get behaviour
is selected. If a parameter is present (and valid) the method
acts as a Set method.

=head2 Probes(@probes_list)

Get/Set the raw probes list. If no parameter is present, the method
returns the number of probes defined (0 if none). If a list of probes
is given, the list is added to the existing list of probes.

=head2 Parse($filename)

Parse a rsync client log. If no filename is specified, the method
parses the log previsiously set with Log() method. Please take
extra care with the filename. If it does not exists, or is not
a file a exception will be raised (Param::Wrong and File::Open).

=head2 Files()

In scalar context returns the number of transfered files (filtered
by probes list). In list context, returns the list of transfered files.

=head2 RealFiles()

In scalar context returns the number of transfered files. In list
context, returns the list of transfered files.

=head2 Deleted()

In scalar context returns the number of deleted files (filtered
by probes list). In list context, returns the list of deleted files.

=head2 RealDeleted()

In scalar context returns the number of deleted files.
In list context, returns the list of deleted files.

=head2 Speed()

Returns the speed (as reported by rsync [in bytes/sec]) of the 
transfer.

=head2 Size()

Returns the size of the synced content.

=head2 TransfData()

Returns the total number of bytes transfered during the sync session

=head2 Symlinks()

In scalar context returns the number of symlinks (filtered
by probes list). In list context, returns the list of symlinks.

=head2 RealSymlinks()

In scalar context returns the number of symlinks.
In list context, returns the list of symlinks.

=head1 PREREQUISITES

RoPkg::Utils requires perl 5.008 or later and RoPkg::Exceptions class. From CPAN,
you need the Scalar::Util module. At build time Test::More is required for tests (if you don't
plan to use the tests ignore this dependency).

=head1 SEE ALSO

L<RoPkg::Rsync::Node> L<RoPkg::Rsync::ConfFile> L<RoPkg::Exceptions>

=head1 AUTHOR

Subredu Manuel <diablo@iasi.roedu.net>

=head1 LICENSE

Copyright (C) 2005 Subredu Manuel.  All Rights Reserved.
This module is free software; you can redistribute it 
and/or modify it under the same terms as Perl itself.
The LICENSE file contains the full text of the license.

=cut
