#!/usr/bin/perl
#
#  This code was developped by SECIOSS (http://www.secioss.co.jp/).
#
#                 Copyright (C) 2009 SECIOSS CORPORATION
#
#  This program is free software; you can redistribute it and/or
#  modify it under the terms of the GNU Lesser General Public License
#  as published by the Free Software Foundation.

use strict;
use lib '../lib/perl';
use Net::LDAP;
use Net::LDAP::Constant qw(:all);
use Config::General;
use Data::Dumper;

# Configuration
my $CONF = $^O ne 'MSWin32' ? '/opt/secioss/etc/openldap/slapd.conf' : '/secioss/etc/lism-server.conf';

my $config = Config::General->new($CONF);
my %param = $config->getall;

our $URI = 'ldap://localhost:3890';
our $BINDDN = $param{'admindn'};
our $BINDPW = $param{'adminpw'};
our $SUFFIX = $param{'basedn'};

# Attribute
our $OPATTR = 'lismConfigOperation';

sub reload
{
    my ($ldap) = @_;
    my @modlist = ();

    push(@modlist, 'replace', [$OPATTR => 'reload']);

    my $msg = $ldap->modify('cn=config,'.$SUFFIX, changes => [@modlist]);
    my $errcode = $msg->code;
    if ($errcode) {
        print STDERR $msg->error."\n";
        return 1;
    }

    return 0;
}

sub usage
{
    print "Usage: lismconfig reload\n";
    exit 1
}

my $op = $ARGV[0];
my $rc = 0;

my $ldap = Net::LDAP->new($URI);
if (!defined($ldap)) {
    print STDERR "Can't connect to LDAP server\n";
    exit 1;
}

my $msg = $ldap->bind($BINDDN, password => $BINDPW);
my $errcode = $msg->code;
if($errcode) {
    print STDERR $msg->error."\n";
    exit 1;
}

if ($op eq 'reload') {
    $rc = reload($ldap);
} else {
    usage();
}

$ldap->unbind;

if ($rc) {
    print STDERR "Failed to reload LISM\n";
} else {
    print "Succeeded to reload LISM\n";
}

exit $rc;
