#!/usr/bin/perl -w

#----------------------------------------------------------------------
# copyright (C) 2010 Firewall Services
# dani@firewall-services.com
#               
# 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
# 
# Technical support for this program is available from e-smith, inc.
# For details, please visit our web site at www.e-smith.com or
# call us on 1 888 ESMITH 1 (US/Canada toll free) or +1 613 564 8000
#----------------------------------------------------------------------

package esmith;

use strict;
use Errno;
use esmith::ConfigDB;
use esmith::AccountsDB;
use esmith::util;
use Net::LDAP;

my $c = esmith::ConfigDB->open_ro;
my $a = esmith::AccountsDB->open_ro;

my $i = $c->get('ipasserelle');
my $ip = $i->prop('status') || 'disabled';
my $reverse = $i->prop('LdapReverseGroups') || 'disabled';
my $x = 0;

exit (0) if (($ip eq 'disabled') || ($reverse eq 'disabled'));

my $l = $c->get('ldap');
my $status = $l->prop('status') || "disabled";
unless ($status eq "enabled" ){
    warn "Not running action script $0, LDAP service not enabled!\n";
    exit(0);
}

my $hostname = $c->get('SystemName')
    || die("Couldn't determine system name");
$hostname = $hostname->value;

my $domain = $c->get('DomainName')
    || die("Couldn't determine domain name");
$domain = $domain->value;

my @accounts;
my $account;
my $event = shift || die "Event name must be specified";
if ($event eq 'ldap-update' or
    $event eq 'bootstrap-ldap-save' or
    $event =~ m/group\-(create|modify|delete)/){
    @accounts = ($a->users);
    push(@accounts, $a->get('admin'));
}
else{
    my @name = @ARGV;
    die "Account name argument missing." unless scalar (@name) >= 1;

    foreach my $name (@name){
        $account = $a->get($name);
        die "Account $name not found.\n" unless defined $account;
        my $type = $account->prop('type') || "unknown";

        die "Account $name is not a user account; update LDAP entry failed.\n"
            unless ($type eq 'user' or $name eq 'admin');
        push @accounts, $account;
    }
}

my $base = esmith::util::ldapBase ($domain);
my $pw = esmith::util::LdapPassword();

my $ldap = Net::LDAP->new('localhost') or die "$@";

$ldap->bind(
    dn => "cn=root,$base",
    password => $pw
);

my $result;
foreach my $acct (@accounts){   
    my $key = $acct->key;

    # Ensure this account has the iPasserelleUser objectclass
    $result = $ldap->search(
                            base   => "ou=Users,". $base,
                            scope  => 'sub',
                            filter => "uid=$key"
                             );
    $result->code && ($x = 255, warn "Error looking for entry uid=$key,ou=Users,$base: ", $result->error);
    my @oc = ();
    my @oldgroups = ();
    foreach my $entry ($result->all_entries()){
        push @oc, $entry->get_value('objectClass');
        push @oldgroups, $entry->get_value('posixMemberOf');
    }

    unless (grep { $_ =~ /iPasserelleUser/i } @oc){
        push @oc, 'iPasserelleUser';

        $result = $ldap->modify(
                     "uid=$key,ou=Users,$base",
                         replace => {
                             objectClass => \@oc
                         }
              );
        $result->code && ($x = 255, warn "failed to modify entry uid=$key,ou=Users,$base: ", $result->error);
    }

    my @groups = $a->user_group_list($key);
    @oldgroups = sort @oldgroups;
    @groups = sort @groups;
    my $oldgroups = join('\0', @oldgroups);
    my $groups = join('\0', @groups);

    unless ($oldgroups eq $groups){
        $result = $ldap->modify(
                     "uid=$key,ou=Users,$base",
                         replace => {
                             posixMemberOf => \@groups
                         }
              );
        $result->code && ($x = 255, warn "failed to modify entry uid=$key,ou=Users,$base: ", $result->error);
    }
}

$ldap->unbind;

exit ($x);
