#!/bin/sh

set -e

. /usr/share/debconf/confmodule
db_version 2.0
test $DEBIAN_SCRIPT_DEBUG && set -v -x

# Load variables from config files if they exists
[ -f "/etc/default/newpki-server" ] && . /etc/default/newpki-server || true
[ ! -z "$NEWPKI_CONF" -a -e "$NEWPKI_CONF" ] && . $NEWPKI_CONF || true

QUESTIONS="server port username password bindaddress localport logfile debuglevel"
PUB_LDAP="/etc/newpki/modules/libpublication_ldap.0.0.0"

case "$1" in
  configure|reconfigure)
  umask 077
  [ -d /etc/newpki ] || mkdir -m0700 /etc/newpki
  
  if [ ! -e $NEWPKI_CONF ]; then
	echo "# Config file for newpki-server" > $NEWPKI_CONF
	for QUESTION in $QUESTIONS; do
		echo "$QUESTION=" >> $NEWPKI_CONF
	done
  fi

  for QUESTION in $QUESTIONS; do
  	cp -a $NEWPKI_CONF $NEWPKI_CONF.tmp
  	db_get newpki-server/$QUESTION
	sed -e "s|^ *$QUESTION=.*|$QUESTION=$RET|" \
	 < $NEWPKI_CONF > $NEWPKI_CONF.tmp
 	 mv -f $NEWPKI_CONF.tmp $NEWPKI_CONF
  done
  chown -R newpki.newpki /etc/newpki
  [ -e $PUB_LDAP -a -x $PUB_LDAP ] && chmod -x $PUB_LDAP
  umask 066
  db_get mysql-server/start_on_boot
    if [ "$RET" = "true" ]; then
      update-rc.d newpki-server defaults >/dev/null
    else
      # FIXME: doesn't work right now because update-rc.d has a bug!
      update-rc.d -f newpki-server remove >/dev/null
     fi
  ;;

  abort-upgrade|abort-remove|abort-configure)
  ;;

  *)
    echo "postinst called with unknown argument '$1'" >&2
    exit 1
  ;;
esac

# No debhelper, see last lines of configure block from the case statement.

exit 0

