#!/bin/bash

#
# Copyright (C) 2022 Nethesis S.r.l.
# http://www.nethesis.it - nethserver@nethesis.it
#
# This script is part of NethServer.
#
# NethServer is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License,
# or any later version.
#
# NethServer 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with NethServer.  If not, see COPYING.
#

set -e

source /etc/nethserver/agent.env
source "${AGENT_STATE_DIR}"/agent.env
source "${AGENT_STATE_DIR}"/environment
cd "${AGENT_STATE_DIR}/nethserver-mail"
source bind.env

migrate_deps ()
{
    if [[ -f "${AGENT_STATE_DIR}/nethserver-webtop5/bind.env" ]]; then
        command "${AGENT_INSTALL_DIR}/apps/nethserver-webtop5/migrate"
    fi

    if [[ -f "${AGENT_STATE_DIR}/nethserver-roundcubemail/bind.env" ]]; then
        command "${AGENT_INSTALL_DIR}/apps/nethserver-roundcubemail/migrate"
    fi

    if [[ -f "${AGENT_STATE_DIR}/nethserver-sogo/bind.env" ]]; then
        command "${AGENT_INSTALL_DIR}/apps/nethserver-sogo/migrate"
    fi

    if [[ -f "${AGENT_STATE_DIR}/nethserver-mail-getmail/bind.env" ]]; then
        command "${AGENT_INSTALL_DIR}/apps/nethserver-mail-getmail/migrate"
    fi
}

hostname -d > mail_domain.txt
echo "${USER_DOMAIN:?}" > user_domain.txt

/sbin/e-smith/db domains printjson > domains.json
/sbin/e-smith/db accounts printjson > accounts.json
/sbin/e-smith/config printjson postfix > postfix.json
/sbin/e-smith/config printjson dovecot > dovecot.json
/sbin/e-smith/config printjson rspamd > rspamd.json
/sbin/e-smith/config printjson clamd > clamd.json
/sbin/e-smith/db smarthosts printjson > smarthosts.json
/sbin/e-smith/db networks printjson > networks.json
/usr/libexec/nethserver/list-groups | jq keys > groups.json
/usr/libexec/nethserver/list-users | jq keys > users.json

# Ensure endpoint is defined
: ${RSYNC_ENDPOINT:?}
export RSYNC_PASSWORD

# Ensure module ID is defined, and export it for Webtop5
: ${MODULE_INSTANCE_ID:?}
export MAIL_INSTANCE_ID="${MODULE_INSTANCE_ID}"

# Send configuration files
rsync -i --remove-source-files user_domain.txt mail_domain.txt {users,groups,domains,accounts,postfix,dovecot,rspamd,clamd,smarthosts,networks}.json "${RSYNC_ENDPOINT}"/data/state/

if [[ "${MIGRATE_ACTION}" == "finish" ]]; then
    # During the last, "finish" rsync run there must be no changes to
    # contents of maildirs: stop the services early.
    systemctl stop postfix dovecot rspamd || :
fi

# rsync note: using usermap and groupmap arguments because the chown does
# not work. Using the "catchall" range 1-1000 because "*" does not work

# Send mailboxes
rsync -i --archive --usermap=1-1000:100 --groupmap=1-1000:101 --exclude lucene-indexes/ --delete /var/lib/nethserver/vmail/ "${RSYNC_ENDPOINT}"/data/volumes/dovecot-data/

if [[ -f /var/lib/redis/rspamd/dump.rdb ]]; then
    # Fix rspamd-redis volume root dir perms
    rsync -i --archive --usermap=1-1000:100 --groupmap=1-1000:101 --delete --exclude \* /var/lib/redis/rspamd/ "${RSYNC_ENDPOINT}"/data/volumes/rspamd-redis/
    # Send Redis database and rename it properly
    rsync -i --archive --usermap=1-1000:100 --groupmap=1-1000:101 /var/lib/redis/rspamd/dump.rdb "${RSYNC_ENDPOINT}"/data/volumes/rspamd-redis/persistent.rdb
fi

# Overwrite default DKIM key
rsync -i --recursive --perms \
    /etc/opendkim/keys/default.{txt,private} \
    "${RSYNC_ENDPOINT}"/data/state/dkim.migration/

if [[ "${MIGRATE_ACTION}" != "finish" ]]; then
    migrate_deps
    exit 0
fi

# Stop and disable local Mail services
for service in rspamd postfix dovecot opendkim olefy; do
    /sbin/e-smith/config setprop "${service}" status disabled || :
    systemctl disable --now "${service}" || :
done

# Commit Mail migration
rsync "${RSYNC_ENDPOINT}"/terminate

# Wait until the import-module task has completed
ns8-action --attach wait "${IMPORT_TASK_ID}"

SmartHostStatus=$(/sbin/e-smith/config getprop postfix SmartHostStatus)
if [[ "${SmartHostStatus}" == "enabled" ]]; then
    # find the vpn ip address of the mail module
    host=$(ns8-action --attach cluster get-smarthost | jq -r '.mail_server[] | select(.mail_id == "'$MAIL_INSTANCE_ID'") | .host')
    ns8-action --attach cluster set-smarthost '{
    "port": 25,
    "host": "'${host}'",
    "username": "",
    "password": "",
    "enabled": true,
    "encrypt_smtp": "none",
    "tls_verify": false}'
fi

migrate_deps
