#!/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
OPTATTR=lismCmdOption

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
        if [ -n "$modlist" ]; then
            modlist="$modlist
-"
        fi
        modlist="$modlist
replace: $FILTERATTR
$FILTERATTR: $syncfilter"
    fi

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

    if [ $cflag -eq 1 ]; then
        modlist="$modlist
-
replace: $OPTATTR
$OPTATTR: continue"
    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] [-c] {update|read} {all|master|cluster}"
    exit 1
}

cflag=0
while getopts d:f:c OPT
do
    case $OPT in
      d)
        data=$OPTARG
        ;;
      f)
        syncfilter=$OPTARG
        ;;
      c)
        cflag=1
        ;;
      *)
        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
