#!/bin/sh -e

shout() { echo "$0: $@" >&2; }
barf() { shout "fatal: $@"; exit 111; }
safe() { "$@" || barf "cannot $@"; }

here=`env - PATH=$PATH pwd`
mypwd=${here%package}
mypwd=${mypwd%/}
home=`head -1 ${mypwd}/conf-home`

bindir=""
if [ -f ${mypwd}/conf-home ]
then
  bindir="${home}/bin"
fi

sendmail=`which sendmail`
dir=`dirname ${sendmail}`

if [ -L ${sendmail} ] 
then
  cd ${dir}
  safe rm ${sendmail}
  safe ln -s ${bindir}/sendmail sendmail 
  shout "Replaced system's sendmail with ${bindir}/sendmail"
  cd ${mypwd}
else
  cd ${dir}
  safe mv sendmail sendmail_
  safe chmod 000 sendmail_
  safe ln -s ${bindir}/sendmail sendmail 
  shout "Replaced system's sendmail with ${bindir}/sendmail"
  cd ${mypwd}
fi 
  
aliasdir=""
if [ -f ${mypwd}/conf-home ]
then
  aliasdir="${home}/alias"
fi
shout "Setting s/qmail alias-dir: ${aliasdir}"

[ -d "${aliasdir}" ] || safe mkdir -p ${aliasdir}

[ -f ${aliasdir}/.qmail-root ] || safe touch ${aliasdir}/.qmail-root
[ -f ${aliasdir}/.qmail-mailer-daemon ] || safe touch ${aliasdir}/.qmail-mailer-daemon 
[ -f ${aliasdir}/.qmail-postmaster ] || safe touch ${aliasdir}/.qmail-postmaster

if [ -f ${mypwd}/conf-delivery ]
then
  defaultdelivery="`head -1 ${mypwd}/conf-delivery`"
  if [ "x$defaultdelivery" = "x" ]
  then 
    barf "No 'defaultdelivery' defined. Check conf-delivery."
  fi 

  if [ -f "${home}/svc/qmail-send/run" ]
  then
    safe cat ${home}/svc/qmail-send/run | \
      sed -e 's%./Maildir/%`eval $defaultdelivery`%' > run.delivery && \
      mv run.delivery ${home}/svc/qmail-send/run && \
      chmod +x ${home}/svc/qmail-send/run && \
      shout "Setting qmail-start default-delivery: $defaultdelivery"
  fi 
fi

exit 0
