#!/bin/bash
##
## LDAP サーバーを利用したユーザー認証/ユーザー情報参照
## LDAP サーバー情報は /etc/openldap/ldap.conf を参照
##

set -u
set -e

query_attributes=(
  uid
  mail
  mailAlternateAddress
)
ldapsearch_options=()

if [[ $1 == "--auth" ]]; then
  auth="set"
  shift
fi

key="$1"; shift

if [[ $key == *@* ]]; then
  search_filter="(|(mail=$key)(mailAlternateAddress=$key))"

  if [[ ${auth+set} ]]; then
    dn=$(
      ldapsearch \
	-x \
	-LLL \
	-o ldif-wrap=no \
	"$search_filter" \
	dn  \
      |head -n 1 \
      ;
    )
    if [[ -z $dn ]]; then
      echo "$0: ERROR: No such e-mail address: $key" 1>&2
      exit 1
    fi
    ldapsearch_options+=(
      -D "${dn#*: }"
      -y /dev/stdin
    )
  fi
else
  search_filter="(uid=$key)"
  if [[ ${auth+set} ]]; then
    ldapsearch_options+=(
      -D "cn=$key,ou=user,dc=tufs,dc=ac,dc=jp"
      -y /dev/stdin
    )
  fi
fi

ldapsearch \
  -x \
  -LLL \
  -o ldif-wrap=no \
  ${ldapsearch_options[@]+"${ldapsearch_options[@]}"} \
  "$search_filter" \
  ${query_attributes[@]+"${query_attributes[@]}"} \
;

exit "${PIPESTATUS[0]}"

