#!/bin/sh
# SPDX-License-Identifier: MulanPSL-2.0+
# Copyright (c) 2020 Huawei Technologies Co., Ltd. All rights reserved.

[[ $LAB_REPO ]] || LAB_REPO=/c/lab-cbs
[[ $CCI_SRC ]] || $CCI_SRC=/c/cbs

host_list_file=$1
cluster_master=$2
local_host=$(hostname)

if [[ -z $host_list_file ]] || [[ -z $cluster_master ]]
then
	echo "Usage: "
	echo "      ./build-remote-host-info { host list file } { cluster master host }"
	echo "host list file: "
	echo "      /etc/compass-ci/remote-hosts-120"
	echo "      /etc/compass-ci/remote-hosts-w1"
	echo "cluster master hsot: "
	echo "      hostname for master node of k8s cluster"

	exit 1
fi

while read hostname testbox queues
do
	if [[ $hostname =~ ^#.* ]]
	then
		continue
	fi

	echo "Building hostinfo for: $hostname"

	scp $CCI_SRC/sbin/extract-hostinfo root@$hostname:$CCI_SRC/sbin/
	ssh -n root@$hostname -C "sh $CCI_SRC/sbin/extract-hostinfo" > /tmp/$hostname 2> /dev/null

	if ! [[ -e /tmp/$hostname ]] || ! [[ -s /tmp/$hsotname ]]
	then
		echo "===>> Failed to extract hostinfo for $hostname <<==="

		continue
	fi

	if [[ $local_host == $cluster_master ]]
	then
		cp /tmp/$hostname $LAB_REPO/hosts/
	else
		scp /tmp/$hostname root@$cluster_master:$LAB_REPO/hosts/
	fi

	rm -f /tmp/$hostname
done < $host_list_file
