#!/usr/bin/env bash
#
# Copyright (c) 2024 YunoHost Contributors
#
# This file is part of YunoHost (see https://yunohost.org)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#

# Exit hook on subcommand error or unset variable
set -eu

# Source YNH helpers
# shellcheck source=../../helpers/helpers
source /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="$(jq -r '.pop3_enabled' <<< "$YNH_SETTINGS" | int_to_bool)"
    export main_domain=$(cat /etc/yunohost/current_host)
    export domain_list="$YNH_DOMAINS_WITH_MAIL_IN_AND_OUT"

    # adapt config for IPv4-only hosts
    if [[ "$(jq -r '.smtp_allow_ipv6' <<< "$YNH_SETTINGS" | int_to_bool)" == "True" ]] \
    && [[ -f /proc/net/if_inet6 ]]; then
        export ipv6_enabled=True
    else
        export ipv6_enabled=False
    fi

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

    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 \
        || {
             mkdir -p /var/vmail
                                  adduser --system --ingroup mail --uid 500 vmail --home /var/vmail --no-create-home
        }

    # 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

    python3 -c 'from yunohost.app import regen_mail_app_user_config_for_dovecot_and_postfix as r; r(only="dovecot")'

    [ -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" "$(echo "${*:2}" | xargs)"
