#!/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 URI;
use REST::Client;
use JSON::XS;
use YAML::Syck;
use FindBin qw($Bin $Script);
use File::Basename;
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_upload.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');
    $self->{client}      = REST::Client->new();
    $env = $self->{conf}->{default_env} if !($env);

    bless $self, $class;

    return $self;
}

sub run {
    my $self = shift;
    if ( !$file ) {
        $file = $collector->collect_stats;
    }
    else {
        $collector->upload_data;
    }
}

sub get_token {
    my $self = shift;
    my $header = { Content_Type => 'application/x-www-form-urlencoded', };
    $collector->{client}->setHost("https://bulk-ingest-automation-$env-rel.auth.us-east-1.amazoncognito.com");
    my $uri  = '/oauth2/token';
    my $data = {
        client_id     => $collector->{conf}->{client_id},
        client_secret => $collector->{conf}->{client_secret},
        grant_type    => 'client_credentials',
        scope         => 'provision-ingest/write'
    };
    $collector->{client}->POST( $uri, substr( $collector->{client}->buildQuery($data), 1 ), $header );
    if ( $collector->{client}->responseCode() !~ /^20\d$/ ) {
        print "Error on return from session connect";
        die;
    }
    my $response = eval { decode_json( $collector->{client}->responseContent() ) };
    return $response->{access_token};
}

sub upload_data {
    my $self         = shift;
    my $signed_url   = URI->new( $collector->get_signed_url );
    my $file_content = read_file($file);
    $collector->{client}->setHost( 'https://' . $signed_url->host );
    $collector->{client}->PUT( $signed_url->path_query, $file_content );
}

sub get_signed_url {
    my $self = shift;
    my $header = { Authorization => 'Bearer ' . $collector->get_token() };
    $collector->{client}->setHost( $collector->{conf}->{endpoint_host}->{$env} );
    my $uri  = '/prod/provision-ingest/{proxy+}';
    my $data = {
        'datacenter_metadata' => {
            'target_environment' => $env,
            'target_dev_prefix'  => ''
        },
        'data_set'           => $collector->{conf}->{dataset},
        'technical_metadata' => { 'format' => $collector->{conf}->{format} },
        'event_time'         => $collector->{event_time},
        'data_category'      => 'onboarding',
        'data_source'        => $collector->{conf}->{data_source},
        'zone'               => 'landing',
        'frequency'          => $collector->{conf}->{frequency},
        'target_file_name'   => basename($file),
        'brand'              => $collector->{conf}->{brand},
        'request_type'       => 'http'
    };

    $collector->{client}->POST( $uri, encode_json($data), $header );
    if ( $collector->{client}->responseCode() !~ /^20\d$/ ) {
        print "Error on return from session connect";
        die;
    }
    return $collector->{client}->responseContent();
}

sub collect_stats {
    my $self = shift;

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

    my $find_cmd = "find /home/*/tmp/awstats/ -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}" );
    }
    $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;
}
