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

# shellcheck disable=SC1091

set -e

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

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

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

if [[ "${MIGRATE_ACTION}" == "finish" ]]; then
    # During the last, "finish" rsync run there must be no changes to
    # the database: stop the service early.
    systemctl stop tomcat8@webtop
fi

# Check if the ActiveSyncLegacyIds is enabled
legacy_ids=$(/sbin/e-smith/config getprop webtop ActiveSyncLegacyIds)
if [[ "${legacy_ids}" == "enabled" ]]; then
	touch legacy_ids_enabled
	rsync -i --remove-source-files legacy_ids_enabled "${RSYNC_ENDPOINT}"/data/state/
fi

# Sync z-push_state. uid=82:gid=82 maps to www-data:www-data
rsync -i --archive --usermap=1-1000:82 --groupmap=1-1000:82 --delete /var/log/z-push/state/ "${RSYNC_ENDPOINT}"/data/volumes/z-push_state/

# Cleanup bad IMAP config, issue #7371
su - postgres  -c "psql -nqS -P pager=off webtop5 -c \"delete from core.user_settings where service_id='com.sonicle.webtop.mail' and key='host' and value ='localhost';\"" || :

# Sync postgresql webtop5 DB dump
su - postgres -c "pg_dump --format=c webtop5" > webtop5.dump
rsync -zi webtop5.dump "${RSYNC_ENDPOINT}"/data/state/webtop5.dump
rm -vf webtop5.dump

# Sync webtop-home
rsync -i --times --recursive --delete /var/lib/nethserver/webtop/ "${RSYNC_ENDPOINT}"/data/volumes/webtop-home/

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

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

# Stop and disable local Webtop services
/sbin/e-smith/config setprop tomcat8@webtop status disabled || :
systemctl disable --now tomcat8@webtop || :

# Set up web redirects
mkdir -vp webroot
cat - >webroot/index.html <<EOF
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Webtop5 Migration</title>
  </head>
  <body>
    <h1>Webtop5 Migration</h1>
    <p>Site has moved to &#9758; <a href="https://${WEBTOP_VHOST}">${WEBTOP_VHOST}</a></p>
  </body>
</html>
EOF
/sbin/e-smith/expand-template /etc/httpd/conf.d/00ns8migration.conf
httpd -k graceful

# Commit Webtop 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 "$(
    /sbin/e-smith/config printjson webtop |
    jq '.props.ActiveSyncLog |= if . == "EMERGENCY" or . == "ALERT" or . == "CRITICAL" or . == "ERROR" or . == "WARNING" or . == "NOTICE" or . == "INFO" or . == "DEBUG" then . else "ERROR" end' |
    jq '.props.DavServerLog |= if . == "EMERGENCY" or . == "ALERT" or . == "CRITICAL" or . == "ERROR" or . == "WARNING" or . == "NOTICE" or . == "INFO" or . == "DEBUG" then . else "ERROR" end' |
    jq -c \
    --arg hostname "${WEBTOP_VHOST}" \
    --arg mail_domain "$(hostname -d)" \
    --arg mail_module "${MAIL_INSTANCE_ID}" \
    --arg AdminMail "$(/sbin/e-smith/config getprop webtop-pecbridge AdminMail)" \
    '.props | {
        "hostname": $hostname,
        "mail_module": $mail_module,
        "mail_domain": $mail_domain,
        "timezone": .DefaultTimezone,
        "locale": .DefaultLocale,
        "pecbridge_admin_mail": $AdminMail,
        "webapp": {
            "debug": (.Debug == "true"),
            "min_memory": (.MinMemory | tonumber),
            "max_memory": (.MaxMemory | tonumber)
        },
        "webdav": {
            "debug": (.Debug == "true"),
            "loglevel": .DavServerLog
        },
        "zpush": {
            "debug": (.Debug == "true"),
            "loglevel": .ActiveSyncLog
        }
    }')"
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 Webtop..."
done
