#!/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.

source '/usr/local/lism/etc/lismcmd.conf'

SYNCATTR=lismSyncStatus
DATAATTR=lismSyncWrongNode
FILTERATTR=lismSyncFilter

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

    if [ -n "$syncfilter" ]; then
        modlist="$modlist
replace: $FILTERATTR
$FILTERATTR: $syncfilter"
    fi

    if [ -z "$modlist" ]; then
        modlist="replace: $SYNCATTR
$SYNCATTR: sync"
    fi

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

function readsync() {
    if [ -n "$data" ]; then
        filter="($DATAATTR=$data)"
    fi

    if [ -n "$syncfilter" ]; then
        if [ -z "$filter" ]; then
            filter=$syncfilter
        else
            filter="(&$filter($syncfilter))";
        fi
    fi

    if [ -z "$filter" ]; then
        filter="(objectClass=*)"
    fi

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

function usage() {
    echo $"Usage: $0 [-d data] [-f filter] {update|read} {all|master|cluster}"
    exit 1
}

while getopts d:f: OPT
do
    case $OPT in
      d)
        data=$OPTARG
        ;;
      f)
        syncfilter=$OPTARG
        ;;
      *)
        usage
    esac
done
shift `expr $OPTIND - 1`

type=$2
if [ "$type" = "all" ]; then
    dn="cn=sync,$SUFFIX"
elif [ "$type" = "master" -o "$type" = "cluster" ]; then
    dn="cn=$type-sync,$SUFFIX"
else
    usage
fi

case "$1" in
    update)
        updatesync
        ;;
    read)
        readsync
        ;;
    *)
        usage
esac

exit 0
