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

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

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

action=$(echo $data | jq -r '.action')
host=$(echo $data | jq -r '.Host')
user=$(echo $data | jq -r '.User')
password=$(echo $data | jq -r '.Password')
tls_verify=$(echo $data | jq -r '.TLSVerify')
# user domain used to rename the directory.nh to another baseDN
ldap_user_domain=$(echo $data | jq -r '.LdapUserDomain')

if [[ "$action" == "login" ]]; then
    # execute ns8-join

    tmp_output=$(mktemp)
    trap 'rm -f $tmp_output' EXIT
    echo "=========== Join cluster" $(date -R) >>/var/log/ns8-migration.log
    if [ "$tls_verify" = "disabled" ]; then
        /usr/sbin/ns8-join --no-tlsverify "$host" "$user" "$password" "$ldap_user_domain" &>"${tmp_output}"
    else
        /usr/sbin/ns8-join "$host" "$user" "$password" "$ldap_user_domain" &>"${tmp_output}"
    fi

    if [ "$?" -gt 0 ]; then
        cat "${tmp_output}" >> /var/log/ns8-migration.log
        # the attribute "steps":-1 triggers the stream interceptor in nethserver.js:exec() function
        # translate some special chars to avoid parse errors:
        jq -cn --arg msg "$(tr '{}' '()' <${tmp_output})" '{"steps":-1,"id":"1717508984","type":"CommandFailed","message": $msg}'
        echo
        exit 1
    else
        echo "Joined to cluster leader $(/sbin/e-smith/config getprop ns8 Host)" >>/var/log/ns8-migration.log
    fi

elif [[ "$action" == "logout" ]]; then
    # disconnect from ns8 cluster

    /usr/sbin/ns8-leave
    if [ $? -gt 0 ]; then
        error "EventFailed" "See /var/log/messages"
    fi
fi

success
