#!/usr/bin/perl -w

# sync-to: Sync to a second repository after commit
# Usage (from post-commit):
#   $REPOS/hooks/sync-to $REPOS /path/to/target/repository
#
# Created by Greg Hudson based on code by Tom Yu
# Questions to ghudson@mit.edu.

use strict;

sub cmdres($) {
    my ($cmd) = @_;
    my $result = `$cmd`;
    die "$0: $cmd failed with wait status $?\n" if $?;
    return $result;
}

die "Usage: $0 SOURCE-REPOS DEST-REPOS" if (scalar @ARGV != 2);

my $repos = shift @ARGV;
my $destrepos = shift @ARGV;

# Dumb but effective lock.  If multiple people commit at the same
# time, the sync might get behind by a rev, but will catch up next
# time.
my $lock = $destrepos . "/sync-lock";
if (mkdir($lock, 0777)) {
    $@ = "";
    eval {
	my $dest_youngest = cmdres("svnlook youngest $destrepos");
	my $youngest = cmdres("svnlook youngest $repos");
	chomp $youngest;
	chomp $dest_youngest;
	if ($youngest > $dest_youngest) {
	    $dest_youngest++;
	    cmdres("svnadmin dump -q --incremental --deltas " .
		   "-r$dest_youngest:$youngest $repos " .
		   "| svnadmin load -q $destrepos");
	}
    };

    rmdir($lock);
    die $@ if $@;
}

1;
