#!/bin/bash

set -e

. /usr/share/yunohost/helpers

do_pre_regen() {
    pending_dir=$1

    cd /usr/share/yunohost/conf/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 'email.pop3.pop3_enabled')"
    export main_domain=$(cat /etc/yunohost/current_host)
    export domain_list="$YNH_DOMAINS"

    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
}

do_$1_regen ${@:2}
