#!/usr/bin/perl -w
#----------------------------------------------------------------------
# vim: ft=perl ts=2 sw=2 et:
#----------------------------------------------------------------------
#
# Copyright (C) 2012 - Marco Hess <marco.hess@through-ip.com>
#
# This file is part of the "Git Repositories" panel in the
# SME Server server-manager panel to configure git repositories.
#
# This program 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 2 of the License, or
# (at your option) any later version.
#
# This program 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 this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
#
#----------------------------------------------------------------------

package esmith;

use strict;
use Errno;
use esmith::util;

#------------------------------------------------------------
# Delete the user or group from access list on git repositories
#------------------------------------------------------------

my $event = $ARGV [0];
my $item  = $ARGV [1];

die "User or Group name argument missing." 
  unless defined ($item);

my @entries = qw();
if ($event eq 'user-delete') {
  # Setup to scan for users
  @entries = qw(UsersWrite UsersRead);
} elsif ($event eq 'group-delete') {
  # Setup to scan for groups
  @entries = qw(GroupsWrite GroupsRead);
} else {
  die "Invalid event: \"$event\" for \"$item\" .";
}

use esmith::GitDB;

my $git_db = esmith::GitDB->open() or
  die "Couldn't open GitDB\n";

my @repositories = $git_db->get_all_by_prop( 'type' => 'repository' );

GIT_REPOSITORY: foreach my $repository ( (@repositories) )
{
  my $repository_rec = $git_db->get( $repository->key() ) || next GIT_REPOSITORY;

  foreach my $entry (@entries) {
    my $members = $repository_rec->prop($entry);
    my @members = split (/,/, $members);
    @members = grep (!/^$item$/, @members);
    $repository_rec->set_prop( $entry, join(',', @members) );
  }
  event_signal( "git-repository-modify", $repository->key() );
}

exit(0);
