#!/usr/bin/perl

=encoding UTF-8
=cut

=head1 DESCRIPTION

=cut

# common modules
use strict;
use warnings FATAL => 'all';
use feature 'say';
use utf8;
use open qw(:std :utf8);

use Carp;
use HTTP::Tiny;
use JSON::PP;
use Moment;
use File::Slurp;

sub save_to_auto_delete_log {
    my ($data) = @_;

    my $json_coder = JSON::PP
        ->new
        ->canonical
        ;

    my $now = Moment->now();

    my $log_line = $json_coder->encode($data) . "\n";

    write_file(
        sprintf('/local/creator/log/auto_delete.%s.jsonl', $now->get_d()),
        {
            append => 1,
        },
        $log_line,
    );
}

# main
sub main {

    my $url = 'http://127.0.0.1:29167/api/3/betas/';
    my $response = HTTP::Tiny->new()->get($url);

    if ($response->{success}) {

        my $betas = decode_json $response->{content};
        my @betas_with_ttl = grep { defined($_->{ttl}) } @{$betas};

        foreach my $beta (@betas_with_ttl) {

            my $is_beta_in_correct_status = grep {$_ eq $beta->{status}} qw(
                build_fail
                running
                stopped
            );

            next unless $is_beta_in_correct_status;

            my $now = Moment->now();
            my $created = Moment->new( iso_string => $beta->{created} );

            if ( ($created->get_timestamp() + $beta->{ttl}) < $now->get_timestamp() ){
                my $response = HTTP::Tiny->new()->request(
                    'DELETE',
                    'http://127.0.0.1:29167/api/3/betas/' . $beta->{port}
                );

                save_to_auto_delete_log({
                    timestamp => $now->get_iso_string(),
                    port => $beta->{port},
                    original_beta_info => $beta,
                    delete_status => $response->{status},
                });

            }
        }
    }

}
main();
__END__
