#!/bin/bash
#
# Mutt - LDAP Lookup Script
#
#  Copyright (c) 2004, Deives Michellis
#   All rights reserved.
#
#   Redistribution and use in source and binary forms, with or without
#   modification, are permitted provided that the following conditions are
#   met:
#     * Redistributions of source code must retain the above copyright
#       notice, this list of conditions and the following disclaimer.
#     * Redistributions in binary form must reproduce the above copyright
#       notice, this list of conditions and the following disclaimer in
#       the documentation and/or other materials provided with the
#       distribution.
#     * Neither the name of the Deives Michellis nor the names of its
#       contributors may be used to endorse or promote products derived
#       from this software without specific prior written permission.
#
#   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
#   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
#   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
#   A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
#   OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
#   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
#   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
#   DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
#   THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
#   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
#   OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# ChangeLog
# - 20040609
#   Versao 0.1 - Suporte a LDAP e AliasFile

# Resources config file
#MUTTSOURCES=~/.mutt-sources
MUTTSOURCES=~/.mutt/ldap.conf
# --- formato do arquivo ---
# # Informa que a fonte de dados eh um LDAP
# Ldap
# # O Host
# host: 10.1.0.5
#host: 128.180.2.34
# # A BaseDN do LDAP
#basedn: MYBASEDN
#basedn: lehigh.edu
# # O nome de Catalogo que aparece na consulta
# sourcename: Exchange
# # Caso seja necessario fazer login no LDAP
# binddn: cn=FULANO, dc=LALALA, dc=com, dc=br
#binddn: cn=lehigh, dc=lehigh, dc=lehigh, dc=edu
# bindpw: MYPASS
# 
# # Configuracao para arquivo local de aliases
# ALIAS
# aliasfile: ~/.mutt-aliasrc
# sourcename: Local Alias
# 
# 
# # Deixe SEMPRE uma linha em branco no fim do arquivo#
# --- fim do formato de arquivo ---

search_ldap() {
  VIEWED=0
  if [ "$BINDDN" != "" ]; then
    LDAPOPTS="-D \"$BINDDN\" -w \"$BINDPW\" "
  else
    LDAPOPTS=""
  fi  
  if [ "$SOURCENAME" != "" ]; then
    SOURCENAME="\t$SOURCENAME"
  fi  

  ldapsearch -x -D "$BINDDN" -w "$BINDPW" -b "$BASEDN" -h "$HOST" "(|(mail=$QUERY)(cn=$QUERY)(sn=$QUERY))" mail cn -LLL | (
    while true; do 
      read ldaplinha || break
      if [ "`echo $ldaplinha | cut -d: -f1 | tr 'A-Z' 'a-z'`" = "cn" ]; then
        CN=`echo $ldaplinha | cut -d: -f2- | sed -e 's/^ *//gi'`
        VIEWED=0
      elif [ "`echo $ldaplinha | cut -d: -f1 | tr 'A-Z' 'a-z'`" = "mail" ]; then
        MAILADDR=`echo $ldaplinha | cut -d: -f2-| sed -e 's/^ *//g'`
        VIEWED=0
      fi  
      if [ `echo -n $ldaplinha | wc -c` -le 1 ]; then
        if [ "$MAILADDR" != "" ]; then
          echo -e "$MAILADDR\t$CN$SOURCENAME"
        fi  
        MAILADDR=""
        CN=""
        VIEWED=1
      fi  
    done  
    if [ $VIEWED -eq 0 ]; then
      if [ "$MAILADDR" != "" ]; then
        echo -e "$MAILADDR\t$CN$SOURCENAME"
      fi  
    fi
  )
}

search_alias(){
	echo "searching alias"
  if [ "$SOURCENAME" != "" ]; then
    # Dirty hack for SED
    SOURCENAME="`echo -e '\t'`$SOURCENAME"
  fi  
  eval "MYALIASFILE=$ALIASFILE"
  if [ -e $MYALIASFILE ]; then
    grep -i "$ALIASQUERY" $MYALIASFILE | sed -e "s/^alias [^ ]* \(.*\) <\(.*\)>/\2`echo -e '\t'`\1$SOURCENAME/gi"
  fi  
}

QUERY="*$@*"
ALIASQUERY="$@"

BASEDN=""
HOST=""
SOURCENAME=""
BINDDN=""
BINDPW=""
BACKEND=""

echo "Searching..."
cat $MUTTSOURCES | (
  while true; do
    read SOURCES || break
    KEY=`echo $SOURCES | cut -d: -f1 | tr 'A-Z' 'a-z' | tr -d ' '`
    VALUE=`echo $SOURCES | cut -d: -f2- | sed -e 's/^ *//g'`
    SOURCES_=`echo $SOURCES | tr 'A-Z' 'a-z' | sed -e 's/^ *//g'`

    case "$SOURCES_" in
      ldap)
        BACKEND=ldap
        BASEDN=""; HOST=""; SOURCENAME=""; BINDPW=""; BINDDN=""; SOURCENAME=""; ALIASFILE="";
      ;;
      alias)
        BACKEND=alias
        BASEDN=""; HOST=""; SOURCENAME=""; BINDPW=""; BINDDN=""; SOURCENAME=""; ALIASFILE="";
      ;;
    esac
    case "$KEY" in
      host)
        HOST="$VALUE"
      ;;
      basedn)
        BASEDN="$VALUE"
      ;;
      sourcename)
        SOURCENAME="$VALUE"
      ;;
      bindpw)
        BINDPW="$VALUE"
      ;;
      binddn)
        BINDDN="$VALUE"
      ;;
      aliasfile)
        ALIASFILE="$VALUE"
      ;;
    esac

    if [ "$SOURCES_" = "" ]; then
      case "$BACKEND" in
        ldap)
          search_ldap
        ;;  
        alias)
          search_alias
        ;;  
      esac
      BACKEND=""; BASEDN=""; HOST=""; SOURCENAME=""; BINDPW=""; BINDDN=""; SOURCENAME=""; ALIASFILE="";
    fi  
  done
) | sort 
