#! /bin/bash
set -e
unset sed setfacl chown echo ln chmod rm

SYSTEMUID=$(getent passwd S-1-5-18 | sed -e 's/[^:]*:[^:]*:\([0-9]*\):.*$/\1/')
ADMINSGID=$(getent group S-1-5-32-544 | sed -e 's/[^:]*:[^:]*:\([0-9]*\):.*$/\1/')
if [ -z "${SYSTEMUID}" -o -z "${ADMINSGID}" ]
then
  echo "ERROR: Cannot find SYSTEM and/or ADMINS SIDS"
fi

setfacl -m u::rw-,g::rw-,o:r-- /etc/defaults/etc/exim.conf
[ -n "${SYSTEMUID}" -a -n "${ADMINSGID}" ] && chown "${SYSTEMUID}:${ADMINSGID}" /etc/defaults/etc/exim.conf

# If /etc/exim.conf does not exist, initialize

if [ ! -e /etc/exim.conf ]
then
  # Point exim to exim-config to increase the probability it will be executed
  if [ ! -e /usr/bin/exim-config ]
  then
    echo "ERROR: /usr/bin/exim-config does not exist."
  else
    ln -sf /usr/bin/exim-config /usr/bin/exim
  fi

  mkdir -p /var/spool/exim /var/log/exim
  chmod 1777 /var/spool/exim /var/log/exim
  [ -n "${SYSTEMUID}" -a -n "${ADMINSGID}" ] && chown "${SYSTEMUID}:${ADMINSGID}" /var/spool/exim /var/log/exim
 
  if [ ! -e /var/spool/mail ]
  then
     mkdir -p /var/spool/mail
     chmod 1777 /var/spool/mail
     [ -n "${SYSTEMUID}" -a -n "${ADMINSGID}" ] && chown "${SYSTEMUID}:${ADMINSGID}" /var/spool/mail
  fi

else
  # Remove any /usr/bin/exim.exe symlink masking /usr/bin/exim
  # Its existence has been reported but not explained.
  if [ -L /usr/bin/exim.exe ]
  then
    rm -fv /usr/bin/exim.exe
  fi

  # If /usr/bin/mailq and /usr/bin/newaliases do not exist, create them
  # This is to preserve existing installations where the links were in the tar file
  if [ ! -e /usr/bin/mailq -a ! -L /usr/bin/mailq ]
  then
    ln -s exim /usr/bin/mailq
  fi

  if [ ! -e /usr/bin/newaliases -a ! -L /usr/bin/newaliases ]
  then
    ln -s exim /usr/bin/newaliases
  fi
fi

