#!/bin/bash
set -e

# TODO: .... everything ...

# todo check for $1 and to overwrite the config ...
if [[ -z "${MAIL_DOMAIN}" ]]; then
  echo "ERROR: MAIL_DOMAIN parameter not set ... exit ..."
  exit 1
fi

if [ ! -f "/etc/dovecot/dovecot.conf" ]; then
  # Copy default config
  echo "Copying default config from /etc/dovecot.dist"
  cp -R /etc/dovecot.dist/* /etc/dovecot/
fi

INIT_STATE_FILE="/etc/dovecot/dovecot-init-done"

if [ ! -f ${INIT_STATE_FILE} ]; then

  echo "Executing init-config script (dovecot-backend) "
  echo "$0 $@"

  echo "Creating user and group: vmail"
  groupadd -g 5000 vmail
  useradd -u 5000 -g 5000 -m -d /home/vmail -s /bin/false vmail
  adduser dovecot vmail

  # Create log dir and adjust permissions
  mkdir -p /var/log/dovecot
  touch /var/log/dovecot/debug.log
  touch /var/log/dovecot/info.log
  touch /var/log/dovecot/error.log

  chown -R vmail:dovecot /var/log/dovecot*

  echo "Creating directory for dovecot acl informations"
  mkdir -p /var/lib/dovecot/db
  chmod 0770 /var/lib/dovecot

  echo "Creating dictionary for shared namespace"
  touch /var/lib/dovecot/db/shared-mailboxes.db

  echo "Creating virtual directories"
  mkdir -p /var/lib/dovecot/virtual/all
  chmod -R 700 /var/lib/dovecot/virtual

  echo "*
  -INBOX/Trash
  -INBOX/Trash/*
  -INBOX/Spam
  -INBOX/Spam/*
    all" > /var/lib/dovecot/virtual/all/dovecot-virtual

  chown -R vmail:vmail /var/lib/dovecot

  LDA_PATH="/usr/lib/dovecot/dovecot-lda"
  echo "dovecot     unix     -     n     n     -     -     pipe" >> /etc/postfix/master.cf
  echo "  flags=DRhu user=vmail:vmail argv=${LDA_PATH} -f \${sender} -d \${user}" >> /etc/postfix/master.cf

  echo "$(date)" > ${INIT_STATE_FILE}
fi

if [[ "${MAIL_DEBUG_LOG}" == "1" ]]; then
  echo "Enabling debug logging for dovecot ..."
  echo "debug_log_path = /var/log/dovecot/debug.log" >> /etc/dovecot/conf.d/10-logging.conf
  echo "auth_verbose = yes" >> /etc/dovecot/conf.d/10-logging.conf
  echo "mail_debug = yes" >> /etc/dovecot/conf.d/10-logging.conf

fi



echo "Configure postfix main.cf"
postconf -e "myhostname = dovecot"
postconf -e "smtpd_use_tls = no"
postconf -e "myorigin = \$mydomain"
postconf -e "mydestination = "
postconf -e "relayhost = "\$mydomain
#postconf -e "smtpd_tls_cert_file=${SSL_DIR}/certs/${FQDN}.crt"
#postconf -e "smtpd_tls_key_file=${SSL_DIR}/private/${FQDN}.key"
postconf -e "dovecot_destination_recipient_limit = 1"
postconf -e "virtual_mailbox_domains = ${MAIL_DOMAIN}"
postconf -e "virtual_transport = dovecot"
postconf -e "myorigin = \$mydomain"
postconf -e "mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128 ${ENV_SUBNET}"
# set home permissions every time ...
chown -R vmail:vmail /home/vmail
chmod 2770 /home/vmail
