#!/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-getmail"
source bind.env

# Ensure the mail module is defined
: "${MAIL_INSTANCE_ID:?}"

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

# Sync the getmail e-smith database
rm -vf getmail.json
/sbin/e-smith/db getmail printjson > getmail.json
rsync -zi  getmail.json "${RSYNC_ENDPOINT}"/data/state/getmail.json

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

# disabled getmail service
for key in $(/usr/sbin/e-smith/db getmail keys)
do
  /usr/sbin/e-smith/db getmail setprop "$key" status "disabled"
done

# expand the getmail configuration with disabled status
/usr/sbin/e-smith/signal-event nethserver-getmail-save

# Obtain the Mail module UUID for configure-module:
mail_instance_uuid=$(ns8-action --attach "module/${MAIL_INSTANCE_ID}" list-service-providers \
  "$(printf '{"service":"imap", "transport":"tcp", "filter":{"module_id":"%s"}}' "${MAIL_INSTANCE_ID}")" \
  | jq -r '.[0].module_uuid')

# Obtain the Mail module host (local IP) for configure-module:
mail_instance_host=$(ns8-action --attach "module/${MAIL_INSTANCE_ID}" list-service-providers \
  "$(printf '{"service":"imap", "transport":"tcp", "filter":{"module_id":"%s"}}' "${MAIL_INSTANCE_ID}")" \
  | jq -r '.[0].host')

# Assert required vars are set
: "${IMPORT_TASK_ID:?}" "${mail_instance_uuid:?}" "${mail_instance_host:?}"

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

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

# Repeat the configure-module if it fails because mail module is not found
while ! ns8-action --attach "module/${MODULE_INSTANCE_ID}" configure-module "$(
    jq -n -c \
    --arg mail_server "${mail_instance_uuid}" \
    --arg mail_host "${mail_instance_host}" \
    '{
      "mail_host": $mail_host,
      "mail_server": $mail_server
    }')"
do
    exit_code="$?"
    if [[ "${exit_code}" != 3 ]]; then
        exit "${exit_code}"
    fi
    sleep 5
    echo "[NOTICE] Module ${MAIL_INSTANCE_ID} seems not ready: trying again to configure imapsync..."
done
