#!/bin/sh

if [ -n "$EX4DEBUG" ]; then
  echo "now debugging $0 $@"
  set -x
fi

# Only do anything if exim4 is actually installed
if [ ! -x /usr/lib/exim4/exim4 ]; then
  exit 0
fi

SPOOLDIR="$(exim4 -bP spool_directory | sed 's/.*=[[:space:]]\(.*\)/\1/')"
# Uncomment the following lines to get daily e-mail reports
#if [ -x /usr/sbin/eximstats ]; then
#  eximstats </var/log/exim4/mainlog \
#                    | mail postmaster -s"$(hostname) Daily email activity report"
#fi


# run tidydb as Debian-exim:Debian-exim.
if [ -x /usr/sbin/exim_tidydb ]; then
  cd $SPOOLDIR/db || exit 1
  find $SPOOLDIR/db -maxdepth 1 -name '*.lockfile' -or -type f \
    -printf '%f\0' | \
      xargs -0r -n 1 \
      start-stop-daemon --start --exec /usr/sbin/exim_tidydb \
      --chuid Debian-exim:Debian-exim -- $SPOOLDIR > /dev/null
fi

# regenerate $SPOOLDIR/gnutls-params
# As this can take _very_ long on machines with little entropy, we limit
# the maximum runtime to 2*$CERTTOOLTIMEOUT seconds and keep using the
# old file otherwise.
CERTTOOLTIMEOUT=1800
if [ -e $SPOOLDIR/gnutls-params ] ; then
  if [ -x /usr/bin/certtool ] ; then
    start-stop-daemon --start --exec /usr/share/exim4/exim4_refresh_gnutls-params \
      --chuid Debian-exim:Debian-exim -- ${CERTTOOLTIMEOUT}
  else
    rm -f $SPOOLDIR/gnutls-params
  fi
fi
