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

fqdn=${USER_DOMAIN:?}
ldap_suffix=dc=$(echo "$fqdn" | sed 's/\./,dc=/g')
# Extract the hostname (part before the first dot)
host=${USER_DOMAIN%%.*}
# Extract the domain (part after the first dot)
domain=${USER_DOMAIN#*.}

ldapservice_password=$(< /var/lib/nethserver/secrets/ldapservice)
(
    umask 077
    # The LDAP_SUFFIX can be probed with the following command
    # ldapsearch -x -b '' -s base -H ldap://127.0.0.1 namingContexts
    # We assume the local LDAP account provider was provisioned by NS7 and the
    # hardcoded values for LDAP_DOMAIN and LDAP_SUFFIX are valid.
    cat - >import.env <<EOF
LDAP_SVCUSER=ldapservice
LDAP_SVCPASS=${ldapservice_password}
LDAP_DOMAIN=${fqdn}
LDAP_SUFFIX=${ldap_suffix}
EOF

    # Generate .ldif data dump
    /usr/sbin/slapcat -o ldif-wrap=no -n 2 | \
        python3 "${AGENT_INSTALL_DIR}"/apps/account-provider/ldap/ns8fixschema.py3 > dump-mdb0.ldif
)

# replace dc=directory,dc=nh by ldap_suffix
sed -i "s/dc=directory,dc=nh/${ldap_suffix}/g" dump-mdb0.ldif
# replace dc: directory by dc: host
sed -i "s/^dc: directory/dc: $host/" dump-mdb0.ldif 

# Send import.env
rsync -i import.env "${RSYNC_ENDPOINT:?}"/data/state/import.env

# Send database
rsync -tri dump-mdb0.ldif "${RSYNC_ENDPOINT}"/data/volumes/data/dump-mdb0.ldif

# Clean up .ldif and .env files
rm -vf dump-mdb0.ldif import.env

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

# Remove temporary external user domain
ns8-action --attach cluster remove-external-domain "$(printf '{"domain":"%s"}' $fqdn)" || :

# Commit DC migration
rsync -v "${RSYNC_ENDPOINT}"/terminate

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

# Stop local LDAP provider (slapd) and disable it permanently
/sbin/e-smith/config setprop slapd status disabled
systemctl disable --now slapd || :

