#!/bin/bash
# SPDX-License-Identifier: MulanPSL-2.0+
# Copyright (c) 2020 Huawei Technologies Co., Ltd. All rights reserved.
# For your reference only.
# It's better to run the below scripts step by step.

namespace=$1
line=${namespace##*ems}

export deploy_k8s=true

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

set_cluster_ip()
{
	local container=$1
	local host_name=$2
	
	cluster_ip=$(cat /etc/compass-ci/service/k8s-env.yaml | grep "$host_name" | sed -n "${line}p" |awk '{print $NF}')
	file=$CCI_SRC/container/$container/k8s/service.yaml
	[[ $container =~ srv-http ]] && file=$CCI_SRC/container/srv-http/k8s/${container##*srv-http-}-service.yaml
	sed -i "s#clusterIP:.*#clusterIP: ${cluster_ip}#g" $file
 }

start_service()
{
	set_cluster_ip "dag"                     "DAG_HOST"
	set_cluster_ip "publisher"               "PUBLISHER_HOST"
	set_cluster_ip "result-webdav"           "RESULT_WEBDAV_HOST"
	set_cluster_ip "srv-http-repositories"   "SRV_HTTP_REPOSITORIES_HOST"
	set_cluster_ip "srv-http-result"         "SRV_HTTP_RESULT_HOST"
	
	for i in new-repo dag extract-stats publisher result-webdav
	do
		cd $CCI_SRC/container/$i
		./start
	done
	
	for i in repositories result
	do
		create_one -f $CCI_SRC/container/srv-http/k8s/$i-deployment.yaml -n $namespace
		create_one -f $CCI_SRC/container/srv-http/k8s/$i-service.yaml -n $namespace
	done
}

create_one()
{
	local params=$*
	kubectl delete $params >/dev/null 2>&1
	kubectl create $params
}

kubectl_create()
{
	master=$(cat /etc/compass-ci/setup.yaml | grep "^master: " | awk -F'master: ' '{print $2}')
	sed -i "s#dag.ems1#dag.$namespace#g" $CCI_SRC/container/configmap.yaml
	sed -i "s#nodeName: $master#nodeName: $HOSTNAME#g" $CCI_SRC/container/*/k8s/*deployment.yaml
	create_one ns $namespace
	create_one -f $CCI_SRC/container/configmap.yaml -n $namespace
	create_one -f $CCI_SRC/container/secrets.yaml -n $namespace
}

cd $CCI_SRC/sparrow || exit

0-package/install
1-storage/tiny
1-storage/permission
2-network/iptables
3-code/dev-env "$namespace"
. /etc/profile.d/compass.sh
kubectl_create
start_service
