#!/bin/ash
# *********************************************************************
# slapd-search: experimental NoSQL shell back-end for slapd(8) SEARCH .
#
# Copyright (c) 2006,2007,2009 Carlo Strozzi
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 2 dated June, 1991.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
# *********************************************************************

# Get local settings and apply defaults.
: ${TMPDIR:=/tmp} ${NOSQL_CHARSET:=utf-8}
: ${NOSQL_INSTALL:=@NOSQL_INSTALL@}
: ${SWU_INSTALL:=@SWU_INSTALL@}
: ${PATH:=@LOCAL_PATH@}

# If this program is called by slapd(8) we cannot be sure that
# the command PATH includes what we need so let's double-check.

which slapdtonbl >/dev/null || . $NOSQL_INSTALL/etc/nosql.rc

export NOSQL_INSTALL SWU_INSTALL PATH TMPDIR NOSQL_CHARSET

slapdExit () {
   [ $# -eq 0 ] && set - 0
   [ $1 -eq 0 ] && echo ""
   echo "RESULT"
   echo "code: $1"
   exit $1
}

# Required arguments:
#
# 1. target directory
# 2. table symbolic name
# 3. database schema, expressed either in full- or relative-path

if [ $# -ne 3 ]
then
   echo "usage: slapd-search <directory> <table> <schema>" >&2
   slapdExit 1
fi

# The target NoSQL database directory must be accessible.
cd "$1" || slapdExit 1

out_tmp=`mktemp $TMPDIR/nosql.XXXXXX` || slapdExit 1
trap "rm -f $out_tmp" 0
trap "exit 2" 1 2 3 15

slapdtonbl --all "$2" | nblparser "$3" "$3" | sh > $out_tmp

istable --allow-duplicates --input $out_tmp || slapdExit $?

# Special characters need to be UTF-8 encoded in LDIF. Also,
# slapd(8) seems to be quite picky regarding unknown characters
# in the data, so it is safer to just tell iconv(1) to skip them.
#
# See http://www.openldap.org/lists/openldap-software/200202/msg00534.html

tabletolist --ldif --input $out_tmp | iconv -c -f $NOSQL_CHARSET -t utf-8

slapdExit 0

# EOF
