#!/bin/bash

set -e

. /usr/share/yunohost/helpers

do_pre_regen() {
  pending_dir=$1

  cd /usr/share/yunohost/templates/dovecot

  dovecot_dir="${pending_dir}/etc/dovecot"
  mkdir -p "${dovecot_dir}/global_script"

  # copy simple conf files
  cp dovecot-ldap.conf "${dovecot_dir}/dovecot-ldap.conf"
  cp dovecot.sieve "${dovecot_dir}/global_script/dovecot.sieve"

  export pop3_enabled="$(yunohost settings get 'pop3.enabled')"
  export main_domain=$(cat /etc/yunohost/current_host)

  ynh_render_template "dovecot.conf" "${dovecot_dir}/dovecot.conf"

  # adapt it for IPv4-only hosts
  if [ ! -f /proc/net/if_inet6 ]; then
    sed -i \
      's/^\(listen =\).*/\1 */' \
      "${dovecot_dir}/dovecot.conf"
  fi

  mkdir -p "${dovecot_dir}/yunohost.d"
  cp pre-ext.conf "${dovecot_dir}/yunohost.d"
  cp post-ext.conf "${dovecot_dir}/yunohost.d"
}

do_post_regen() {
  regen_conf_files=$1

  mkdir -p "/etc/dovecot/yunohost.d/pre-ext.d"
  mkdir -p "/etc/dovecot/yunohost.d/post-ext.d"

  # create vmail user
  id vmail > /dev/null 2>&1 \
    || adduser --system --ingroup mail --uid 500 vmail --home /var/vmail --no-create-home

  # Delete legacy home for vmail that existed in the past but was empty, poluting /home/
  [ ! -e /home/vmail ] || rmdir --ignore-fail-on-non-empty /home/vmail

  # fix permissions
  chown -R vmail:mail /etc/dovecot/global_script
  chmod 770 /etc/dovecot/global_script
  chown root:mail /var/mail
  chmod 1775 /var/mail

  [ -z "$regen_conf_files" ] && exit 0

  # compile sieve script
  [[ "$regen_conf_files" =~ dovecot\.sieve ]] && {
    sievec /etc/dovecot/global_script/dovecot.sieve
    chown -R vmail:mail /etc/dovecot/global_script
  }

  systemctl restart dovecot
}

FORCE=${2:-0}
DRY_RUN=${3:-0}

case "$1" in
  pre)
    do_pre_regen $4
    ;;
  post)
    do_post_regen $4
    ;;
  *)
    echo "hook called with unknown argument \`$1'" >&2
    exit 1
    ;;
esac

exit 0
