#!/usr/bin/perl
#  -*-Perl-*-  (for Emacs)    vim:set filetype=perl:  (for vim)
#======================================================================#

# Name:   pc_svn-transfer-changes
# Author: PABourdin, Christmas present for Matthias
# Date:   27-Dec-2023
# ID:     $Id$
# Description:
# Transfers local changes in one SVN checkout to another "fresh" checkout.

use strict;

my $progname = $0;
$progname =~ s|^\S*/||;

my $usage="Usage:  $progname <path_old> <path_new>\n\nTransfers all local changes from one SVN working copy at <path_old> into a fresh working copy at <path_new>.\n";
if (@ARGV != 2) { die $usage; }

my $old = $ARGV[0];
my $new = $ARGV[1];

$old =~ s|/+$||s;
$new =~ s|/+$||s;

if (!-d $old || !-d "$old/.svn") { die "ERROR: no SVN working copy at source '".$old."'."; }
if (!-d $new || !-d "$new/.svn") { die "ERROR: no SVN working copy at destination '".$new."'."; }

my $clean = `cd "$new" && svn status | grep -P "^M "`;
chomp ($clean);
if ($clean ne "") { die "ERROR: there are modified files in destination '".$new."':\n".$clean."\n=> Please submit your changes first and 'svn up' both copies!\n"; }

my $stat = `cd "$old" && svn status | grep -P "^M "`;
chomp ($stat);
if ($stat eq "") { print "no modified files in source '".$old."'\n"; exit (0); }

my $local = `cd "$old" && svn info --show-item revision .`;
chomp ($local);
my $URL = `cd "$old" && svn info --show-item url .`;
chomp ($URL);
#my $remote = `svn info --show-item revision $URL`;
#chomp ($remote);
#if ($local ne $remote) { die "ERROR: first please 'svn up' at source '".$old."'\n"; }

my @files = split (/\n\s*/s, $stat);
print "Processing files:\n";
foreach my $line (@files) {
	if ($line =~ /^M\s+(.*)$/s) {
		my $file = $1;
		print "$file\n";
		my $cp = `cp -f "$old/$file" "$new/$file" 2>&1`;
		chomp ($cp);
		if ($cp) { die "ERROR: ".$cp."\n"; }
		my $touch = `touch "$new/$file" 2>&1`;
		chomp ($touch);
		if ($touch) { die "ERROR: ".$touch."\n"; }
	}
}
print "Done.\nAll files transferred successfully!\n";

exit (0);