#!/usr/bin/perl -w

package esmith;

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

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

# Don't attempt to update ldap unles master
exit(0) unless ($c->get('ldap')->prop('Authentication') || 'disabled') eq 'enabled';

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 $domain = $c->get('DomainName')
|| die("Couldn't determine domain name");
$domain = $domain->value;

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 $smb = $c->get('smb');
my $domName = $smb->prop('Workgroup') || 'sme-server';
if ( ($smb->prop('ServerRole') || 'WS') eq 'WS' )
{
    $domName = $smb->prop('ServerName') || 'sme-server';
}

my $result = $ldap->search( base => $base, 
    filter => "(&(objectClass=sambaDomain)(!(sambaDomainName=$domName)))", 
    scope => 'one' 
);
die "failed looking up sambaDomainName entry: ", $result->error if $result->code;

foreach ($result->entries)
{
    $_->delete;
    $_->update($ldap);
}
