#!/usr/bin/perl

=head1 NAME
    
    direct-mass-dmove

=head1 DESCRIPTION
    
    dmove-ит пакеты, переданные ему direct-release to_dmove
    использовать через pipe
    например: direct-release --app java-api5 -s stable to_dmove | direct-mass-dmove

=cut

use strict;
use warnings;

use Data::Dumper;
use ProjectSpecific;
use Getopt::Long;

eval "use Release::${ProjectSpecific::PROJECT}";
die "can't load Release module for project ${ProjectSpecific::PROJECT}:\n$@" if $@;

GetOptions("help" => \&usage);

my $res = {};

my $dmove_cmd = "dt-dist";

my %to_dmove;
my %repos_hash;
my $direction = "";
my $repo = "";
my $inside_flag = 0;
while (my $str = <>){
    chomp $str;
    if ($str eq ">>>>>>>>>>>>>") {
        $inside_flag = 1 - $inside_flag;
        next;
    }
    next if !$inside_flag || $str =~ /^\s*$/;

    if ($str =~ /^# *(\w+) *-> *(\w+)/){
        $direction = "$1_$2";
        $dmove_cmd = dmove_cmd() if $direction =~ /^(unstable_stable|testing_stable|prestable_stable)$/;
        next;
    }
    if ($str =~ /^### (direct-\w+):$/) {
        $repo = $1;
        next;
    }
    die "unsupported direction '$direction' for dmove, stop\n" unless $direction =~ /^(unstable_testing|unstable_stable|testing_stable|prestable_stable)$/;
    $repos_hash{$repo} = 1;
    push @{$to_dmove{$direction}{$repo}}, $str;
}

for $repo (keys %repos_hash) {
    my @to_dmove_testing = (@{$to_dmove{unstable_testing}{$repo}||[]}, @{$to_dmove{unstable_stable}{$repo}||[]});
    if ( @to_dmove_testing > 0 ){
        open(my $dmove_testing, "|-", "$dmove_cmd dmove_testing_from_file -r $repo -");
        print $dmove_testing $_."\n" or die for @to_dmove_testing;
        close $dmove_testing or die;
    }

    my @to_dmove_stable = (@{$to_dmove{unstable_stable}{$repo}||[]}, @{$to_dmove{testing_stable}{$repo}||[]});
    if ( @to_dmove_stable > 0 ){
        open(my $dmove_stable, "|-", "$dmove_cmd dmove_stable_from_file -r $repo -");
        print $dmove_stable $_."\n" or die for @to_dmove_stable;
        close $dmove_stable or die;
    }

    my @to_dmove_prestable_stable = (@{$to_dmove{prestable_stable}{$repo}||[]});
    if ( @to_dmove_prestable_stable > 0 ){
        open(my $dmove_prestable_stable, "|-", "$dmove_cmd dmove_prestable_stable_from_file -r $repo -");
        print $dmove_prestable_stable $_."\n" or die for @to_dmove_prestable_stable;
        close $dmove_prestable_stable or die;
    }
}
    
exit(0);

sub usage {
    system("podselect -section NAME -section DESCRIPTION $0 | pod2text-utf8 >&2");
    exit(1);
}

