#!/usr/bin/perl

package AWStats_Collector;

use strict;
use warnings;
use Capture::Tiny ':all';
use File::Path qw(make_path remove_tree);
use File::Copy "cp";
use File::Slurp;
use DateTime;
use JSON::XS;
use YAML::Syck;
use FindBin qw($Bin $Script);
use File::Basename;
use POSIX qw(strftime);
use Getopt::Long;
use Pod::Usage;
use Data::Dumper;

$| = 1;

my ( $env, $file, $help );
GetOptions(
    'env=s'  => \$env,
    'file=s' => \$file,
    'help'   => \$help
);

pod2usage( -exitval => 0, -verbose => 2, noperldoc => 1 ) if ($help);

my $collector = AWStats_Collector->new( { name => $Script } );

$collector->run;

sub new {
    my ( $class, $args ) = @_;
    my $self = {
        name        => $args->{name},
        script_conf => '/opt/eig_linux/etc/awstats_collector.yaml',
    };

    $self->{conf} = eval { LoadFile( $self->{script_conf} ) }
      or die( strftime( '%b %d %G %T', localtime ) . "Failed loading $self->{script_conf} " . $! );

    my $dt = DateTime->now( time_zone => 'local' );
    $self->{event_time}  = $dt->strftime('%Y-%m-%dT%H:%M:%S');
    $self->{date_prefix} = $dt->subtract( months => 1 )->strftime('%m%Y');
    $env                 = $self->{conf}->{default_env} if !($env);

    bless $self, $class;

    return $self;
}

sub run {
    my $self = shift;
    print strftime( '%b %d %G %T', localtime ) . " Starting collector run\n";
    if ( !$file ) {
        $file = $collector->collect_stats;
    }
    else {
        $collector->upload_data;
    }
    print strftime( '%b %d %G %T', localtime ) . " Completed collector run\n";
}

sub upload_data {
    my $self     = shift;
    my $sftp_cmd = qq|sftp -o "CheckHostIP=no" -o "IdentityFile=$collector->{conf}->{ssh_key}" $collector->{conf}->{user}\@$collector->{conf}->{endpoint_host}->{$env} <<< "put $file"|;
    my ( $stdout, $stderr, $exit ) = capture {
        system($sftp_cmd );
    };
    if ($exit) {
        print strftime( '%b %d %G %T', localtime ) . " upload_data Error on sftp: " . $stderr . "\n";
        exit 0;
    }
    print strftime( '%b %d %G %T', localtime ) . " Uploaded $file to " . $collector->{conf}->{endpoint_host}->{$env} . "\n";
    return 1;
}

sub collect_stats {
    my $self = shift;

    if ( !-d "$collector->{conf}->{staging_dir}/$collector->{date_prefix}/ssl" ) {
        make_path( "$collector->{conf}->{staging_dir}/$collector->{date_prefix}/ssl", { mode => 0700, verbose => 1 } );
    }

    # Non SSL stats
    my $find_cmd = "find /home/*/tmp/awstats/ -maxdepth 1 -name awstats$collector->{date_prefix}\*.txt";
    chomp( my @output = qx{$find_cmd} );
    foreach my $stats_file (@output) {
        cp( $stats_file, "$collector->{conf}->{staging_dir}/$collector->{date_prefix}" );
    }

    # SSL stats
    $find_cmd = "find /home/*/tmp/awstats/ssl/ -maxdepth 1 -name awstats$collector->{date_prefix}\*.txt";
    chomp( @output = qx{$find_cmd} );
    foreach my $stats_file (@output) {
        cp( $stats_file, "$collector->{conf}->{staging_dir}/$collector->{date_prefix}/ssl" );
    }

    $file = "$collector->{conf}->{staging_dir}/$ENV{'HOSTNAME'}-awstats$collector->{date_prefix}.tgz";
    qx{tar --transform=s#var/awstats_staging#$ENV{'HOSTNAME'}# -zcf $file $collector->{conf}->{staging_dir}/$collector->{date_prefix}};
    $collector->upload_data;
    return 1;
}
