#!/usr/bin/perl
#

use strict;

use SVN2GitPatch;

my $svn_repo_path = "/tmp/svn/samba.repo";
my $authors_file = "svn-authors";

my $svn_branch = "branches/SAMBA_4_0";
my $svn_start_rev = 25600;
my $basepath = "/tmp/svn/v4-0-test";

my $patch_path = "$basepath/patches";
my $last_svn_rev_file = "$patch_path/latest.svnrev";
my $git_repo_path = "$basepath/git";

$ENV{LANG} = "en_US.UTF-8";

my $r = SVN2GitPatch->new($svn_repo_path, $authors_file);

sub load_last_svn_rev($;$)
{
	my ($file, $default_rev) = @_;

	$default_rev = 0 unless defined($default_rev);

	my $v = util::FileLoad($file);

	$v = $default_rev if $v eq "";
	$v *= 1;
	$v = $default_rev if $v == 0;

	print "load_last_svn_rev: $v\n";
	return $v;
}

sub save_last_svn_rev($$)
{
	my ($file, $rev) = @_;
	util::FileSave($file, $rev);
	print "save_last_svn_rev: $rev\n";
}

my $last_rev = $r->get_last_svn_rev($svn_branch);
my $start_rev = load_last_svn_rev($last_svn_rev_file, $svn_start_rev);
my $revs = $r->get_missing_svn_revs($svn_branch, $start_rev);

print "start: $start_rev last: $last_rev\n";

foreach my $rev (sort keys %{$revs}) {
	print "Get patch for rev: $rev\n";
	my $p = $r->get_git_patch($revs->{$rev}->{branch}, $rev);

	if (defined($p->{git_patch})) {
		my $patch_path = "$patch_path/$rev.patch";
		open(PATCH, ">$patch_path") or
			die ("failed to $patch_path for write");
		print PATCH $p->{git_patch}."\n";
		close PATCH;

		my $applycmd = "cd $git_repo_path && git am --whitespace=nowarn --binary $patch_path";

		print "Apply $rev.patch\n";
		my $apply = `$applycmd` or die "$applycmd: failed";
	}

	save_last_svn_rev($last_svn_rev_file, $rev);
}
