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

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

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

if [[ $# != 2 ]]
then
	echo "Usage: "
	echo "     ./remote-install-multi-docker { host_list_file } { cluster_master }"
	echo "Example: "
	echo "     ./remote-install-multi-docker /etc/compass-ci/remote-hosts-120 cbs-120 "

	exit 1
fi

source ${CCI_SRC}/lib/log.sh
source ${CCI_SRC}/lib/pub-shell-function.sh

reslov_conf=/etc/resolv.conf
dns_server=$(kubectl get cm node-local-dns -n kube-system -o yaml | grep __PILLAR__DNS__SERVER__ | head -n 1 | awk '{print $2}')
if ! grep -q "nameserver ${dns_server}" ${reslov_conf};then
	sed -i '1i options ndots:5' ${reslov_conf}
	sed -i '1i search ems1.svc.cluster.local svc.cluster.local cluster.local' ${reslov_conf}
	sed -i "1i nameserver ${dns_server}" ${reslov_conf}
fi

while read -u 3 hostname compute queues password
do
	[[ $hostname =~ ^# ]] && continue

	(
		test_host_reachable $hostname || continue

		test_host_trusted $hostname || {
			config_trust root $hostname $password || {
				echo "Config trust failed!"
				echo "Continue next"

				continue
			}
		}


		ssh root@$hostname -C "umask 002; mkdir -p /c/"
		rsync -ra --delete $LKP_SRC $CCI_SRC root@$hostname:/c/
		rsync -ra /etc/compass-ci root@$hostname:/etc/
		rsync -ra ${reslov_conf} root@$hostname:/${reslov_conf}
		ssh root@$hostname -C "cd /c/cbs/sparrow/k8s; sh install-multi-docker $compute $queues"
		ssh -n root@$hostname -C "sh /c/cbs/sbin/extract-hostinfo" > /tmp/$hostname 2> /dev/null

		if ! [[ -e /tmp/$hostname ]] || ! [[ -s /tmp/$hsotname ]]
		then
			log_info "Failed to extract hostinfo for $hostname"
		else
			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
		fi
	) &
done 3< $host_list_file

wait

log_info "finish"
