#!/usr/bin/perl -w
use strict;
use Getopt::Long qw(GetOptions);
use Git;

my $repo = Git->repository;
my $rev = '@';
my $from;
GetOptions("rev=s" => \$rev,
	"from=s" => \$from) or
	die("Error in command line arguments\n");

my @patches;

if (scalar @ARGV) {
	@patches = @ARGV;
} else {
	@patches = $repo->command('diff', '--name-only', $rev, '--',
		'patches.*');
}

die 'nothing to do' if (scalar @patches == 0);

my $regexp = join "|", @patches;

my @patches_sorted = $repo->command('grep', '-Eh', $regexp, 'series.conf');
map { s/\s//g; $_ } @patches_sorted;

sub dump_diff(@) {
	my %count;

	foreach my $e (@_) {
		$count{$e}++;
	}

	foreach my $e (keys %count) {
		print STDERR "\t$e\n" if ($count{$e} != 2);
	}
}

if (scalar @patches != scalar @patches_sorted) {
	print STDERR "problems:\n";
	dump_diff(@patches, @patches_sorted);
	die 'count of patches does not match: ', scalar @patches, " != ", scalar @patches_sorted;
}

if (defined $from) {
	while (scalar @patches_sorted && $patches_sorted[0] ne $from) {
		shift @patches_sorted;
	}
}

my $out_dir;
my $file = $patches_sorted[0];

print "Applying up to '$file'\n";

open(SEQ, "./scripts/sequence-patch.sh --quilt --dir=/dev/shm/jslaby/ --fast $file |") or die 'cannot run ./scripts/sequence-patch.sh';
while (<SEQ>) {
	$out_dir = $1 if (/Creating tree in (.*)/);
	print;
}
close(SEQ);

chdir "$out_dir";

foreach my $file (@patches_sorted) {
	system('quilt', 'push', '--fuzz=0', $file) == 0 or
		die "push in $out_dir";
	system('./patches/scripts/refresh_patch.sh') == 0 or
		die "refresh in $out_dir";
}

system('quilt', 'push', '--fuzz=0', '-a') == 0 or die "push -a in $out_dir";

1;
