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

[ "$CCI_SRC" ] || export CCI_SRC=$(git rev-parse --show-toplevel)

. $CCI_SRC/lib/log.sh

check_server_ip()
{
	mkdir -p /etc/compass-ci
	cp -a $CCI_SRC/sparrow/setup.yaml /etc/compass-ci/setup.yaml
	[ -z "$server_ip" ] && . 0-package/read-config
	[ -z "$server_ip" ] && {
		log_error "ENV \$server_ip doesn't exist, please config $CCI_SRC/sparrow/setup.yaml"
		exit 1
	}
}

install_env()
{
	cd $CCI_SRC/sparrow || return
	check_server_ip
	0-package/install
	1-storage/tiny
	5-build/ipxe &
	1-storage/permission
	2-network/br0
	2-network/br1
	2-network/iptables
	3-code/git
	3-code/dev-env
	7-systemd/iBMA-install
	. /etc/profile.d/compass.sh
}

boot_ipxe()
{
	SCHED_HOST=$server_ip
	sed -i "s%172.17.0.1%${SCHED_HOST}%g" /tftpboot/boot.ipxe
	sed -i "s%3000%${SCHED_PORT:-3000}%g" /tftpboot/boot.ipxe
}

run_service()
{
	(
		cd $CCI_SRC/container/dnsmasq || return
		./build
		./start
		boot_ipxe
	)&
	(
		cd $CCI_SRC/container/qemu-efi || return
		./build
		./install
	)&
	(
		cd $CCI_SRC/container/fluentd-base || return
		./build

		cd $CCI_SRC/container/sub-fluentd || return
		./build
		./start
	)&
}

check_service()
{
	for service in dnsmasq sub-fluentd
	do
		docker ps | grep -q $service || {
			log_error "failed to start container $service"
			exit 1
		}
	done

	docker images | grep -q qemu-efi || {
		log_error "failed to build container qemu-efi"
		exit 1
	}
}

check_cmd()
{
	[ -n "$(command -v lockfile-create)" ] || {
		log_error "command not found: lockfile-create"
		exit 1
	}
}

main()
{
	install_env
	run_service
	wait
	check_service
	check_cmd
}

main
