#!/usr/bin/perl

=head1 NAME

    migration-to-tracker -- создать или найти тикет на миграцию в стартреке

=head1 SYNOPSIS

    # создать тикет на миграцию в большом директе
    migration-to-tracker -a direct my-migration.yaml
    
    # создать тикет на миграцию в java-приложении
    migration-to-tracker -a java-web my-migration.yaml

=cut

use strict;
use warnings;

use utf8;

use open qw/:std :encoding(UTF-8)/;

use Getopt::Long;
use Startrek::Client::Easy;
use YAML;
use Yandex::Shell;
use XML::LibXML;
eval "use MigratorB::Parse";
eval "use DirectRelease::Migrations qw(find_migration_ticket)";
use Encode qw/decode_utf8/;
use ProjectSpecific qw/svn_url/;

our $ARCADIA_URL = 'svn+ssh://arcadia.yandex.ru/arc';

run() unless caller();

sub run {
    my $opt = parse_options();
    
    my $st = Startrek::Client::Easy->new();

    my @svn_deploy_paths;
    if ($opt->{app} =~ m!java-(.+)!i) {
        my $primary_svn_dir = YAML::LoadFile("/etc/yandex-direct/direct-apps.conf.yaml")->{apps}->{$opt->{app}}->{"primary-svn-dir"};
        push @svn_deploy_paths, "$ARCADIA_URL/trunk/arcadia/".$primary_svn_dir."/deploy";
        push @svn_deploy_paths, " $ARCADIA_URL/trunk/arcadia/direct/deploy";
    } else {
        push @svn_deploy_paths, (svn_url('trunk') . '/deploy');
    }

    my $migration_text;
    for my $svn_deploy_path (@svn_deploy_paths) {
        my $stdout = yash_qx("svn list $svn_deploy_path");
        if ($stdout =~ m!^$opt->{migration_filename}$!m) {
            my $full_migration_filepath = "$svn_deploy_path/$opt->{migration_filename}";
            print "Found migration $full_migration_filepath\n";
            $migration_text = yash_qx("svn cat $full_migration_filepath");
            if (!utf8::is_utf8($migration_text)) {
                utf8::decode($migration_text);
            }
            $migration_text .= "\n" unless $migration_text =~ /\n$/;
            $migration_text = MigratorB::Parse::to_text($opt->{migration_filename} => $migration_text);
            last;
        }
    }

    if (!$migration_text) {
        print "\nCan't find migration $opt->{migration_filename}, stop\n";
        exit(0);
    }

    my $ticket;
    eval {
        $ticket = find_migration_ticket($opt->{migration_filename}, $opt->{app});
    };

    my $ticket_description = "%%\n$migration_text\n%%"
        . "----\n"
        . "!!Внимание!!! Данный тикет создан ручным запуском migration-to-tracker\n"
        . "Прочтите ((https://wiki.yandex-team.ru/direct/development/howto/directmigr/#migration-to-trackerskript инструкцию))\n";
    if ($@ || !$ticket) {
        # если тикета нет
        my $res = $st->do(
            create => 1,
            type => 'task',
            description => $ticket_description,
            summary => "$opt->{app}: Миграция $opt->{migration_filename}",
            queue => "DIRECTMIGR",
        );
        print "\nCreated ticket: $res (https://st.yandex-team.ru/$res)\n";

    } else {
        # если тикет есть
        if ($ticket->{description} ne $ticket_description) {
            my $res = $st->do(
                key => $ticket->{key},
                description => $ticket_description,
            );
            print "\nUpdated ticket: $ticket->{key} (https://st.yandex-team.ru/$ticket->{key})\n";
        } else {
            print "\nFound up-to-date ticket: $ticket->{key} (https://st.yandex-team.ru/$ticket->{key})\n";
        }
    }

    exit(0); 
}

sub parse_options {
    my %O;
    GetOptions(
        'iknowwhatiamdoing' => \$O{iknowwhatiamdoing},
        'a|app=s' => \$O{app},
        'h|help' => sub { system("podselect -section SYNOPSIS -section DESCRIPTION $0 | pod2text-utf8 >&2"); exit 0 },
    ) || die "can't parse options, stop\n";
    defined && utf8::decode($_) for values(%O);

    die "This script is not intended for use, please read https://nda.ya.ru/t/wNAnzqLH3VxitW" unless $O{iknowwhatiamdoing};

    die "expecting app name" unless $O{app};
    $O{migration_filename} = $ARGV[0];
    return \%O;
}

1;
