#!/bin/bash

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="/usr/lib/newpki-server/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
  
  # remove password from the debconf database
  db_set newpki-server/password ""

  chown -R newpki:newpki /etc/newpki
  [ -e $PUB_LDAP -a -x $PUB_LDAP ] && chmod -x $PUB_LDAP
  umask 066
##### do not rely on mysql-server/start_on_boot (see #322886)
#  cp -a $NEWPKI_CONF $NEWPKI_CONF.tmp
#  db_get mysql-server/start_on_boot
#  AUTOSTART="$RET"
#  sed -e "s|^ *LAUNCH_AT_STARTUP=.*|LAUNCH_AT_STARTUP=$AUTOSTART|" \
#    < $NEWPKI_CONF > $NEWPKI_CONF.tmp
#  mv -f $NEWPKI_CONF.tmp $NEWPKI_CONF
  ;;

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

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

# dh_installdeb will replace this with shell code automatically
# generated by other debhelper scripts.

#DEBHELPER#

# Don't wait on wzdftpd to close file handles
db_stop

exit 0

