#!/usr/bin/perl
use strict;
use warnings;
use Getopt::Long;
use Term::ANSIColor qw(colored);
use Term::ReadLine;

my $from = 'Kernel:stable';
my $to = 'openSUSE:Factory';
my $review;

GetOptions("from=s" => \$from,
	"to=s"   => \$to,
	"review" => \$review,
) or die("Error in command line arguments\n");

my @opts = qw/cmd=diff unified=1 expand=0 filelimit=0 file[]=kernel-source.changes/;
push @opts, "oproject=$to";

my @cmd = qw/osc api -X POST/;
push @cmd, "/source/$from/kernel-source?" . join "&", @opts;

open(my $DIFF, '-|', @cmd) or die "cannot rdiff: ", join(" ", @cmd);
# skip header
for (my $i = 0; $i < 4; $i++) {
	<$DIFF>;
}
my %bsc;
my $start = 1;
while (<$DIFF>) {
	map { $bsc{$_} = 1 } /(?:bsc|boo|fate)#\d+|jsc#\w+-\d+'/g if /^\+/;
	if (/\+-{10,}/) {
		$start = 1;
		print "\n";
		next;
	}
	if (/^\+/) {
		print colored($_, 'red') if ($start == 3);
		print $_ if ($start > 3 && $start < 5);
		$start++;
	}
}
close $DIFF;

my $term = new Term::ReadLine('sl_sr_kernel');

print "\n";

my $msg = $term->readline(colored("Write summary:", 'yellow') . " ");
$msg .= "; bugs: " . join(" ", sort keys %bsc) if (scalar %bsc);
print "\n$msg\n";

my $reply = $term->readline(colored('OK?', 'yellow') . " ");
exit 0 unless defined $reply;

@cmd = ('osc', 'sr', '-m', $msg, $from, 'kernel-source', $to);

open(my $sr, '-|', @cmd) or die "cannot run ", join(" ", @cmd);
while (<$sr>) {
	print;
	if (my ($id) = /.* id ([0-9]+)/) {
		system('oscopen', $id);
		system(qw/osc review add -m/, qq|do not check in, let's see how this goes|, '-U', 'jirislaby', $id) if ($review);
	}
}
close $sr;

1;
