#!/usr/bin/perl -w -I /home/latest/repos/slaby-scripts/perl
use strict;
use Git;
use StableHelper;
use Getopt::Long qw(GetOptions);
use Term::ANSIColor qw(colored color);

my $host;
my $refdate;
my $sdir = glob '~/linux';
my $susebranch = "SLE15-SP1";
my $susedir;
GetOptions("branch=s" => \$susebranch,
	   "dir=s" => \$susedir,
	   "ldir=s" => \$sdir,
	   "refdate=s" => \$refdate,
	   "host=s" => \$host);
die "invalid arguments" if (!scalar @ARGV || !defined $susedir ||
	(defined $refdate && !defined $host) ||
	(!defined $refdate && defined $host));

$susebranch = "origin/" . $susebranch;

my $suserepo = Git->repository($susedir);
my $susetop = $suserepo->command_oneline('rev-parse', $susebranch);
my $repo = Git->repository();

print colored("Parsing Git-commits from ", 'green'),
	colored("$susedir#$susebranch\n", 'yellow');

my %git_commits = map {
	if (/^Git-commit:\s*([0-9a-f]{40})/) {
		$1 => 1;
	} else {
		print "invalid git-commit: $_\n";
	}
} $suserepo->command('grep', '-h', '^Git-commit:', $susebranch, '--', 'patches.*');

print color('green'), "Parsing ", scalar @ARGV, " patches\n", color('reset');

my @to_apply;

foreach my $patch (@ARGV) {
	print "  Handling $patch\n";
	open(FILE, "<", $patch) || die "cannot open $patch";
	my @header = ();
	my $has_delim = 0;
	while (my $line = <FILE>) {
		chomp $line;
		if ($line eq "---") {
			$has_delim = 1;
			last;
		}
		push @header, $line;
	}
	close FILE;

	die "no '---' in $patch" unless ($has_delim);

	my @SHAs = StableHelper::get_upstream_commits(@header);
	if (scalar @SHAs == 0) {
		print colored("\tNo SHAS!\n", 'red');
	} elsif (scalar @SHAs == 1 && exists $git_commits{$SHAs[0]}) {
		$repo->command_noisy('rm', $patch);
	} else {
		push @to_apply, @SHAs;
	}
}

if (defined $host) {
	print colored("Generating:\n", 'green');

	foreach (@to_apply) {
		my @cmd = ('susegen', '-r', "networking-stable-$refdate", $host, '-1', $_);
		chdir($sdir);
		system(@cmd) == 0 or die "cannot run susegen";
	}
	exit 0;
}

print colored("To be applied:\n", 'green');

foreach (@to_apply) {
	print "$_\n";
}

1;
