#!/bin/bash
#
# shellcheck disable=SC2046,SC2116
#
# Copyright 2023 The qm Authors
#
# This program 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 2
# of the License, or (at your option) any later version.
#
# This program 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 this program; If not, see <http://www.gnu.org/licenses/>.
#

NODES_FOR_TESTING_ARR="${NODES_FOR_TESTING_ARR:-control qm-node1}"
readarray -d ' ' -t NODES_FOR_TESTING <<< "$NODES_FOR_TESTING_ARR"
CONTROL_CONTAINER_NAME="${CONTROL_CONTAINER_NAME:-control}"
WAIT_BLUECHI_AGENT_CONNECT="${WAIT_BLUECHI_AGENT_CONNECT:-5}"

test_bluechi_list_all_units() {

    local bluechictl_cmd

    for node_name in "${NODES_FOR_TESTING[@]}"
    do
        echo
        info_message "Connected to \033[92m${CONTROL_CONTAINER_NAME}\033[0m, listing few systemd units from \033[92m${node_name}\033[0m"
        if [ "${CONTROL_CONTAINER_NAME}" == "host" ]; then
           bluechictl_cmd="bluechictl list-units ${node_name}"
        else
           # It could take some time for qm bluechi-agent to connect
           if [[ "${node_name}" =~ .*qm.* ]];then
              sleep "${WAIT_BLUECHI_AGENT_CONNECT}"
           fi
           bluechictl_cmd="podman exec"
           bluechictl_cmd+=" ${CONTROL_CONTAINER_NAME}"
           bluechictl_cmd+=" bluechictl list-units ${node_name}"
        fi
        cmd_result=$(eval "${bluechictl_cmd}")

        if_error_exit "unable to execute bluechictl command on ${CONTROL_CONTAINER_NAME}"

        if [ "${CONTROL_CONTAINER_NAME}" == "host" -o "${CONTROL_CONTAINER_NAME}" == "autosd" ]; then
           grep -E  "bluechi|qm" <<< ${cmd_result}
        else
           grep -E  "container-|qm.service" <<< ${cmd_result}
        fi
    done
}
