#!/bin/ash
# *********************************************************************
# ldaptolist: turns selected LDAP entries into a NoSQL list.
#	      Requires the OpenLDAP utility 'ldapsearch'.
#
# Copyright (c) 2004,2006 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.
# *********************************************************************
# $Id: ldaptolist,v 1.4 2006/03/10 11:26:13 carlo Exp $

# Get local settings and apply defaults.
: ${NOSQL_INSTALL:=/usr/local/nosql}

EUSAGE='Usage: ldaptolist [options] attr [attr ...] -- [ldapsearch options] filter(s)'

[ $# = 0 ] && { echo "$EUSAGE"; exit 1; }

while :
do
  case $1 in
    -o|--output)	shift; o_file="$1" ;;
    -h|--help)
       grep -v '^#' $NOSQL_INSTALL/help/ldaptolist.txt
       exit 1
    ;;
    --show-copying)
       cat $NOSQL_INSTALL/doc/COPYING
       exit 1
    ;;
    --show-warranty)
       cat $NOSQL_INSTALL/doc/WARRANTY
       exit 1
    ;;
    --)		shift; break ;;
    *)		attlist="$attlist $1" ;;
  esac
  shift
done

if [ -z "$attlist" ]
then
   echo "$EUSAGE"
   exit 1
fi

[ "$o_file" = "" ] || exec > "$o_file"

# Run ldapsearch. Double quotes aroud "$@" are mandatory!!

#echo $# "$@" $attlist ; exit		# uncomment for debugging

ldapsearch -LLL "$@" $attlist | awk -v attlist="$attlist" '
BEGIN{
   sub(/^ */,"",attlist)		# strip trailing blank
   sub(/ *$/,":",attlist)		# strip leading blank
   gsub(/ +/,": ",attlist)		# add colons
   cols=split(attlist,a," ")
}
NR==1 {print ""}
$1==""{
   if (NR < 2) exit(rc=1)	# unexpected output from ldapsearch(1)
   for (i=1; i<=cols; i++) {
       out = a[i] b[tolower(a[i])]
       sub(/:/,"\t",out)
       print out
   }
   delete b
   print ""
   next
}
{x=tolower($1); sub(/[^:]+: */,""); b[x]=$0}
END{
   if (rc) exit(rc)
   # cope with no match input.
   if (NR < 2) {
      print ""
      for (i=1; i<=cols; i++) {
	  sub(/:/,"",a[i])
	  print a[i]
      }
      print ""
   }
}'

exit $?

# End of program.
