#!/usr/bin/perl

use strict;
use warnings;
use JSON qw( decode_json );

=head1 NAME

=encoding utf8

    ждет, пока пакет начнет находиться на dist-е (проиндексируется например)

=head1 DESCRIPTION

    -t, --timeout <int>
        сколько ждать, в секундах; по умолчанию 120 (=2 минуты)

    -s, --sleep <int>
        какими паузами спать, в секундах; по умолчанию 15

    -e, --dist-env <string>
        в какой ветке (environment) должен находиться пакет (unstable/testing/stable)
        опциональный параметр, если не указан - то ищем пакет в любой ветке

    wait-package-on-dist yandex-du-captcha-perl_0.09~dirty-1
    wait-package-on-dist --timeout 0 yandex-direct_1.12345-1
    wait-package-on-dist yandex-direct-dna_0.280.0 --dist-env testing

=cut

use Getopt::Long;
use LWP::UserAgent;
use Net::INET6Glue::INET_is_INET6;

$|++;

run() unless caller();

sub run
{
    my $opt = parse_options();

    my $start = time();
    my $i = 0;
    my $ua = LWP::UserAgent->new;
    while ( 1 ){
        die "too many iterations, stop\n" if $i++ > 600;
        my $now = time;

        print localtime($now)." iteration $i ...\n";
        my $response = $ua->get("http://dist.yandex.ru/api/v1/search?pkg=$opt->{pkg}&ver=$opt->{version}&strict=true");
        my $res = $response->decoded_content;
        if ( $opt->{dist_env} ) {
            my @pkgs = @{ decode_json($res)->{result} };
            my $found;

            foreach my $pkg ( @pkgs ) {
                $found = $pkg->{environment} eq $opt->{dist_env};
                last if $found;
            }
            last if $found;
        } else {
            last if $res =~ /\Q$opt->{pkg}\E/;
        }

        die "timeout exceeded, stop\n" if $now - $start >= $opt->{timeout};
        print "going to sleep for $opt->{sleep} seconds\n";
        sleep($opt->{sleep});

    }

    print "success\n";

    exit 0;
}

sub parse_options
{
    my %O = (
        timeout => 120,
        sleep => 15,
    );

    GetOptions(
        "help" => sub {
            system("podselect -section NAME -section DESCRIPTION -section OPTIONS -section EXAMPLES $0"); 
            exit 0;
        },
        't|timeout=i' => \$O{timeout},
        'e|dist-env=s' => \$O{dist_env},
    ) or die "can't parse options, stop\n";

    $O{pkg} = shift @ARGV;
    ($O{pkg}, $O{version}) = split(/_/, $O{pkg});

    die "too many arguments, stop\n" if @ARGV; 
    die "bad package name '$O{pkg}'" unless $O{pkg} =~ /^[\w\-]+$/;
    die "version is required" unless $O{version};

    return \%O;
}
