#!/bin/sh

set -e

CONFFILE="/etc/nss-ldapd.conf"

# set an option in the configuration file to the specified value
cfg_set()
{
  parameter=$1
  value=$2
  commented=0
  notthere=0
  # check if the parameter is defined
  grep -i -q "^$parameter " $CONFFILE || notthere=1
  if [ "$notthere" = "1" ]
  then
    # check if the parameter is commented out
    if grep -i -q "^#$parameter" $CONFFILE
    then
      notthere=0
      commented=1
    fi
  fi
  # decide what to do
  if [ "$notthere" = "1" ]
  then
    # just append a new line
    echo "$parameter $value" >> $CONFFILE
  else
    # TODO: check if the option is already defined with the value we need
    # replace the existing option
    replacestring="$parameter"
    if [ "$commented" = "1" ]
    then
      replacestring="# *$parameter"
    fi
    # this works as long as any option is specified only once
    # FIXME: also work when option is commented out on multiple lines
    sed -i 's%^'"$replacestring"' .*$%'"$parameter $value"'%i' "$CONFFILE"
  fi
  # we're done
  return 0
}

# disable an option in the configuration file by commenting it out
cfg_disable()
{
  parameter=$1
  # TODO add an option to also remove the option value
  #      (for passwords)
  if grep -i -q "^$parameter " $CONFFILE
  then
    sed -i 's%^\('"$parameter"'.*\)$%#\1%i' "$CONFFILE"
  fi
  # we're done
  return 0
}

# editing nsswitch.conf seems to be ok
# http://lists.debian.org/debian-devel/2007/02/msg00076.html

# check to see if name is configured to do lookups through
# LDAP and enable if not
nss_enable()
{
  name=$1
  if ! grep -q '^'$name':.*ldap.*' /etc/nsswitch.conf
  then
    echo "/etc/nsswitch.conf: enable LDAP lookups for $name" >&2
    if grep -q '^'$name':' /etc/nsswitch.conf
    then
      # modify an existing entry by just adding ldap to the end
      sed -i 's/^\('$name':.*\)[[:space:]]*$/\1 ldap/' /etc/nsswitch.conf
    else
      # append a new line
      printf '%-15s ldap\n' $name':' >> /etc/nsswitch.conf
    fi
  fi
  # we're done
  return 0
}

# remove NSS lookups though LDAP for the specified service
nss_disable()
{
  name=$1
  # these functions also remove the lookup result handling part
  # of the ldap entry (see nsswitch.conf(5))
  if grep -q '^'$name':.*ldap.*' /etc/nsswitch.conf
  then
    echo "/etc/nsswitch.conf: disable LDAP lookups for $name" >&2
    if [ -n "`sed -n '/^'$name':[[:space:]]*ldap[[:space:]]*\(\[[^]]*\]\)*[[:space:]]*$/p' /etc/nsswitch.conf`" ]
    then
      # the name service only maps to ldap, remove the whole line
      sed -i '/^'$name':[[:space:]]*ldap[[:space:]]*\(\[[^]]*\]\)*[[:space:]]*$/d' /etc/nsswitch.conf
    else
      # remove ldap part from existing line, keeping other methods intact
      # TODO: remove trailing space
      sed -i 's/^\('$name':.*\)ldap[[:space:]]*\(\[[^]]*\]\)*[[:space:]]*\(.*\)$/\1\3/' /etc/nsswitch.conf
    fi
  fi
  # we're done
  return 0
}

# create a default configuration file if nothing exists yet
create_config()
{
  if [ ! -e "$CONFFILE" ]
  then
    if [ -f /etc/libnss-ldap.conf ]
    then
      # begin the file by some information as to where it came from
      cat > "$CONFFILE" << EOM
# $CONFFILE
# nss-ldapd configuration file. See nss-ldapd.conf(5)
# for details.
#
# This file was based on existing configuration files
# /etc/libnss-ldap.conf and /etc/libnss-ldap.secret

EOM
      # copy the existing config in place, getting rid
      # of the silly #DEBCONF# lines
      egrep -v '(###DEBCONF###|configuration of this file will be done by debconf|dpkg-reconfigure)' \
        < /etc/libnss-ldap.conf \
        >> "$CONFFILE"
      # also append the secret file if it is present
      if [ -f /etc/libnss-ldap.secret ]
      then
        echo "rootbindpw `cat /etc/libnss-ldap.secret`" >> "$CONFFILE"
      fi
      # disable options that are no longer supported
      cfg_disable host
      cfg_disable port
    else
      # fall back to generating a simple configuration file
      # from this simple template
      # TODO: improve this template
      cat > "$CONFFILE" << EOM
# $CONFFILE
# nss-ldapd configuration file. See nss-ldapd.conf(5)
# for details.

# The location at which the LDAP server(s) should be reachable.
uri ldap://localhost/

# The search base that will be used for all queries.
base dc=example,dc=net

# The LDAP protocol version to use.
ldap_version 3

# The DN to bind with for normal lookups.
binddn cn=annonymous,dc=example,dc=net
bindpw secret

# The DN to bind with for lookups as root.
rootbinddn cn=administrator,dc=example,dc=net
rootbindpw verysecret

# The search scope.
#scope sub

EOM
    fi
  fi
  # we're done
  return 0
}

# real functions begin here
if [ "$1" = "configure" ]
then
  # get configuration data from debconf
  . /usr/share/debconf/confmodule
  # create a default configuration
  create_config
  # set server uri
  db_get libnss-ldapd/ldap-uris
  cfg_set uri "$RET"
  # set search base
  db_get libnss-ldapd/ldap-base
  cfg_set base "$RET"
  # set ldap version
  db_get libnss-ldapd/ldap-version
  cfg_set ldap_version "$RET"
  # set bind dn/pw
  db_get libnss-ldapd/ldap-binddn
  if [ -n "$RET" ]
  then
    cfg_set binddn "$RET"
    db_get libnss-ldapd/ldap-bindpw
    cfg_set bindpw "$RET"
    # remove password from database
    db_set libnss-ldapd/ldap-bindpw ""
  else
    # no binddn/pw, disable options
    cfg_disable binddn
    cfg_disable bindpw
    # FIXME: remove password value from config
  fi
  # set root bind dn/pw
  db_get libnss-ldapd/ldap-rootbinddn
  if [ -n "$RET" ]
  then
    cfg_set rootbinddn "$RET"
    db_get libnss-ldapd/ldap-rootbindpw
    cfg_set rootbindpw "$RET"
    # remove password from database
    db_set libnss-ldapd/ldap-rootbindpw ""
  else
    # no binddn/pw, disable options
    cfg_disable rootbinddn
    cfg_disable rootbindpw
    # FIXME: remove password value from config
  fi
  # modify /etc/nsswitch.conf
  db_get libnss-ldapd/nsswitch
  enablenss=`echo "$RET" | sed 's/,//g'`
  for n in aliases ethers group hosts netgroup networks passwd protocols rpc services shadow
  do
    if echo ' '$enablenss' ' | grep -q ' '$n' '
    then
      nss_enable $n
    else
      nss_disable $n
    fi
  done
  # we're done
  db_stop
  # TODO: fix permissions of configfile if passwords are stored
  # TODO: create backups of /etc/nsswitch.conf and configfile
  #       (probably store orig in tmpfile and if diff install it
  #       as backup)
fi

# restart nscd to pick up changes in nsswitch.conf
# (other processes will have to be restarted manually)
if [ -s /usr/sbin/nscd ]
then
  if [ `pidof -s nscd` ]
  then
    if which invoke-rc.d >/dev/null 2>&1
    then
      invoke-rc.d nscd restart
    else
      /etc/init.d/nscd restart
    fi
  fi
fi

#DEBHELPER#

exit 0