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

. /usr/libexec/nethserver/api/lib/helper_functions

echo '{"progress":"0.00","time":"0.0","exit":0,"event":"migration-sync","state":"running","step":0,"pid":0,"action":""}'

# read json from stdin
data=$(cat /dev/stdin)

app_id=$(jq -r '.app' <<<"$data")
action=$(jq -r '.action' <<<"$data")
migration_config=$(jq -r '.migrationConfig' <<<"$data")

exit_apierror ()
{
    echo '{"pid":0,"status":"failed","event":"migration-sync"}'
    error "ApiFailed" "${action} ${app_id} failed"
}

run_check_import ()
{
    local app_id
    app_id=${1:?}
    if [[ -x "${app_idir}"/check-import ]]; then
        # If the app overrides the check-import script, run it. Some
        # modules like Mail requires it.
        "${app_idir}"/check-import "${app_id}"
    else
        # If the app installation dir has no check-import script,
        # run the automatic check:
        /usr/sbin/ns8-check-import "${app_id}"
    fi
}

trap exit_apierror ERR

source /etc/nethserver/agent.env
source "${AGENT_STATE_DIR:?}/environment"
app_idir="${AGENT_INSTALL_DIR:?}/apps/${app_id}"
app_sdir="${AGENT_STATE_DIR:?}/${app_id}"

set -a # export all variables
MODULE_NODE_ID=$(jq -r '.appNode // 1' <<<"${migration_config}")
# Map input values from migrationConfig to environment variables
if [[ -f "${app_idir}/input-${action}.jq" ]]; then
    eval "$(jq -r -f "${app_idir}/input-${action}.jq" <<<"${migration_config}")"
fi

echo "----------- ${action} ${app_id}" $(date -R) >>/var/log/ns8-migration.log

if [ "$action" == "start" ]; then
    mkdir -vp "${app_sdir}"
    flock "${app_sdir}/syncing.lock" "${app_idir}/bind" &>>/var/log/ns8-migration.log
elif [[ "$action" == "sync" ]]; then
    run_check_import "${app_id}"
    MIGRATE_ACTION="${action}" flock ${app_sdir}/syncing.lock "${app_idir}/migrate" &>>/var/log/ns8-migration.log
elif [[ "$action" == "finish" ]]; then
    run_check_import "${app_id}"
    MIGRATE_ACTION="${action}" flock ${app_sdir}/syncing.lock "${app_idir}/migrate" &>>/var/log/ns8-migration.log
    touch ${app_sdir}/migrated
    if [[ "${app_id}" == "account-provider" ]]; then
        /usr/sbin/ns8-leave
    fi
elif [[ "$action" == "abort" ]]; then
    if [[ "${app_id}" == "nethserver-mail" ]]; then
        # Abort also getmail, roundcube and webtop migration: both apps must be migrated
        # together with the mail server
        if [ -f '/etc/e-smith/db/configuration/defaults/webtop/type' ]; then
            /usr/sbin/ns8-abort nethserver-webtop5 &> /dev/null
        fi
        if [[ -f '/etc/e-smith/db/configuration/defaults/roundcubemail/type' && -d '/var/lib/mysql/roundcubemail' ]]; then
            /usr/sbin/ns8-abort nethserver-roundcubemail &> /dev/null
        fi
        if [ -f '/etc/e-smith/db/configuration/defaults/sogod/type' ]; then
            /usr/sbin/ns8-abort nethserver-sogo &> /dev/null
        fi
        if [ -f '/etc/e-smith/events/actions/nethserver-getmail-conf' ]; then
            /usr/sbin/ns8-abort nethserver-mail-getmail &> /dev/null
        fi
    fi
    /usr/sbin/ns8-abort "${app_id}" &> /dev/null
elif [[ "$action" == "toggle-skip" ]]; then
    /usr/sbin/ns8-toggle-skip "${app_id}"
else
    error "ApiFailed" "unknown action ${action}"
fi

echo '{"progress":"1.00","time":"0.0","exit":0,"event":"migration-sync","state":"done","step":0,"pid":0,"action":""}'
echo '{"pid":0,"status":"success","event":"migration-sync"}'
success
