#!/usr/bin/perl
# ------------------------------------------------------------------------------
# (C) British Crown Copyright 2006-16 Met Office.
#
# This file is part of FCM, tools for managing and building source code.
#
# FCM is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# FCM is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with FCM. If not, see <http://www.gnu.org/licenses/>.
# ------------------------------------------------------------------------------

use strict;
use warnings;

use FindBin;
use lib "$FindBin::Bin/../lib";
use FCM::Admin::System qw{verify_users};
use FCM::System::CM::SVN;
use FCM::Util;

our @IGNORES = qw{Config Rel Share};

my $UTIL = $FCM::Admin::System::UTIL;
my $CM_SYS = FCM::System::CM::SVN->new({'util' => $UTIL});

if (!caller()) {
    main(@ARGV);
}

sub main {
    local(@ARGV) = @_;
    my ($repos, $txn) = @ARGV;

    my %layout_config = $CM_SYS->load_layout_config('file://' . $repos);
    if (!$layout_config{'level-owner-branch'}) {
        return;
    }

    # Get list of new paths
    my %lines_of; # $lines_of{$owner} = [$path, ...]
    LINE:
    for my $line ($CM_SYS->stdout(qw{svnlook changed -t}, $txn, $repos)) {
        my $status = substr($line, 0, 1);
        if ($status eq 'A') {
            my $path = substr($line, 4);
            # $is_local=1
            my $layout = $CM_SYS->get_layout_common($repos, $txn, $path, 1);
            my $owner = $layout->get_branch_owner();
            if ($owner && !grep {$_ eq $owner} @IGNORES) {
                if (!exists($lines_of{$owner})) {
                    $lines_of{$owner} = [];
                }
                push(@{$lines_of{$owner}}, $line);
            }
        }
    }

    # Verify branch owners, if necessary
    my @bad_users = verify_users(keys(%lines_of));
    for my $bad_user (@bad_users) {
        for my $line (@{$lines_of{$bad_user}}) {
            warn("[INVALID BRANCH OWNER] $line\n");
        }
    }
    exit(scalar(@bad_users));
}

1;
__END__

=head1 NAME

pre-commit-verify-branch-owner

=head1 SYNOPSIS

    pre-commit-verify-branch-owner REPOS TXN

=head1 ARGUMENTS

Accept the same arguments as a Subversion pre-commit hook.

=head1 DESCRIPTION

This program ensures that users create a branch with its owner correctly set.

=head1 COPYRIGHT

E<169> Crown copyright Met Office. All rights reserved.

=cut
