#!/usr/bin/perl

use strict;
use warnings;

if (-e ".svn") {
    exec("svnversion",@ARGV);
}

use Getopt::Long;
my $no_newline = 0;
GetOptions("no-newline|n!" => \$no_newline);
my $newline = $no_newline ? "" : "\n";
my $p = shift @ARGV;
$p ||= ".";

my @lines = `svk info $p`;
my @merged = grep {/^Merged From: /} @lines;

unless (@merged) {
    @merged = grep {/^Revision: /} @lines;
    my ($version) = $merged[0] =~ /^Revision: (\d+)/;
    print "$version$newline";
    exit;
}

my ($path, $rev) = $merged[0] =~ /^Merged From: (\S+), Rev. (\d+)/;

my @log = `svk log -l1 -r$rev /$path`;
@log = grep {/\(orig r\d+\)/} @log;

if (@log and $log[0] =~ /\(orig r(\d+)\)/) {
    print "$1$newline";
} else {
    print "$rev$newline";
}
