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

# clean up remote ns8 state
source /var/lib/nethserver/nethserver-ns8-migration/environment
if [[ -n "${USER_DOMAIN}" ]] && [[ -z "${ACCOUNT_PROVIDER_EXTERNAL}" ]]; then
    # Remove the external domain only if the ns8-join procedure created it as a
    # temporary external domain for the migration
    ns8-action --hidden --detach cluster remove-external-domain $(printf '{"domain":"%s"}' "${USER_DOMAIN}") || :
fi

if [[ -n "${NODE_ID}" ]]; then
    ns8-action --detach cluster remove-node $(printf '{"node_id":%d}' "${NODE_ID}") || :
    ns8-action --detach cluster remove-user $(printf '{"user":"%s"}' "ns7admin${NODE_ID}") || :
fi

# reset DB props
/sbin/e-smith/config setprop ns8 Host "" User "" Password "" TLSVerify enabled LeaderIpAddress ""
/sbin/e-smith/config setprop wg-quick@ns8 status disabled Address "" RemoteEndpoint "" RemoteKey "" RemoteNetwork ""

# reset nsdc routes
if [ -f /var/lib/machines/nsdc/etc/systemd/network/green.network ]; then
    /sbin/e-smith/expand-template /var/lib/machines/nsdc/etc/systemd/network/green.network
    systemctl -M nsdc restart systemd-networkd
fi

# clean up agent state directory
find /var/lib/nethserver/nethserver-ns8-migration -type f -not -name index.html | xargs -- rm -vf

# signal event
/sbin/e-smith/signal-event nethserver-ns8-migration-save
# write log
echo "=========== Leave cluster" $(date -R) >>/var/log/ns8-migration.log
