#!/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

do_pre_regen() {
    pending_dir=$1

    cd /usr/share/yunohost/conf/opendkim

    install -D -m 644 opendkim.conf "$pending_dir/etc/opendkim.conf"
}

do_post_regen() {
    mkdir -p /etc/dkim

    # Create / empty those files because we're force-regenerating them
    echo "" > /etc/dkim/keytable
    echo "" > /etc/dkim/signingtable

    # create DKIM key for domains
    for domain in $YNH_DOMAINS_WITH_MAIL_IN_AND_OUT; do
        domain_key="/etc/dkim/${domain}.mail.key"
        if [ ! -f "$domain_key" ]; then
            # We use a 1024 bit size because nsupdate doesn't seem to be able to
            # handle 2048...
            opendkim-genkey --domain="$domain" \
                --selector=mail --directory=/etc/dkim -b 1024
            mv /etc/dkim/mail.private "$domain_key"
            mv /etc/dkim/mail.txt "/etc/dkim/${domain}.mail.txt"
        fi

        echo "mail._domainkey.${domain} ${domain}:mail:${domain_key}" >> /etc/dkim/keytable
        echo "*@$domain mail._domainkey.${domain}" >> /etc/dkim/signingtable
    done

    chown -R opendkim /etc/dkim/
    chmod 700 /etc/dkim/

    systemctl restart opendkim
}

"do_$1_regen" "$(echo "${*:2}" | xargs)"
