#!/bin/sh
#
#  This code was developped by SECIOSS (http://www.secioss.co.jp/).
#
#                 Copyright (C) 2007 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.

URI=ldap://localhost:3890
SUFFIX="dc=lism,dc=com"
BINDDN="cn=Manager,dc=lism,dc=com"
BINDPW=secret
SYNCATTR=description
DATAATTR=ou

type=$2
data=$3

if [ "$type" = "all" ]; then
    dn="cn=sync,$SUFFIX"
elif [ "$type" = "master" -o "$type" = "cluster" ]; then
    dn="cn=$type-sync,$SUFFIX"
else
    echo $"Usage: $0 {update|read} {all|master|cluster} data"
    exit 1;
fi

function updatesync() {
    if [ -z "$data" ]; then
        modlist="replace: $SYNCATTR
$SYNCATTR: sync"
    else
        modlist="delete: $DATAATTR"
        for d in `echo $data | sed "s/,/\n/"`; do
            modlist="$modlist
$DATAATTR: $d"
        done
    fi

    ldapmodify -x -H $URI -D $BINDDN -w $BINDPW \
<< SYNC
dn: $dn
changetype: modify
$modlist
SYNC
}

function readsync() {
    if [ -z "$data" ]; then
        filter="(objectClass=*)"
    else
        filter="(ou=$data)"
    fi

    ldapsearch -x -LLL -H $URI -D $BINDDN -w $BINDPW -b $dn -s base $filter
}

case "$1" in
    update)
        updatesync
        ;;
    read)
        readsync
        ;;
    *)
        echo $"Usage: $0 {update|read} {all|master|cluster} [data]"
esac

exit 0
