#!/bin/bash


. ${LKP_SRC}/lib/debug.sh

root_path="/openEuler_compile_env"
chroot_lkp="${root_path}${LKP_SRC}"

config_env_repo()
{
	rm -rf /etc/yum.repos.d.bak
	mv /etc/yum.repos.d /etc/yum.repos.d.bak
	mkdir -p /etc/yum.repos.d
	export yum_conf="/etc/yum.repos.d/my.repo"
	touch ${yum_conf}
	i=1
	for repo in ${repo_url[@]}
	do
		cat >> ${yum_conf} <<-EOF
		[image_repo_$i]
		name=image_repo_$i
		baseurl=${repo}
		enabled=1
		gpgcheck=0

		EOF
		let i=i+1
	done
}

config_envmaker_repo()
{
	rm -rf /etc/yum.repos.d.bak
	mv /etc/yum.repos.d /etc/yum.repos.d.bak
	mkdir -p /etc/yum.repos.d
	export yum_conf="/etc/yum.repos.d/my.repo"
	touch ${yum_conf}
	ARCH="$(uname -i)"
	# The source of 22.03-lts-sp2 has envmaker
	cat >> ${yum_conf} <<-EOF
	[everything]
	name=everything
	baseurl=http://repo.openeuler.org/openEuler-22.03-LTS-SP2/everything/$ARCH/
	enabled=1
	gpgcheck=0

	EOF
}

init_compile_env()
{
	if rpm -q envmaker &> /dev/null; then
		yum remove -y envmaker
	fi
	yum install envmaker -y -c ${yum_conf} || die "install envmaker error."
	config_env_repo

	ARCH="$(uname -i)"
	repo_conf="/opt/envmaker/config/${ARCH}/openEuler_repo.conf"
	env_file_name="openEuler_compile_env_${ARCH}-1.0.0.tar.gz"

	cd /opt/envmaker/
	cp ${yum_conf} ${repo_conf}
	bash envmaker.sh -p openEuler_compile_env_${ARCH} -v 1.0.0
	if [ $? -ne 0 ];then
		die "make compile env failed"
	fi

	cd "/opt/envmaker/result/$(date +%Y)"*
	if [ ! -s "${env_file_name}" ];then
		die "make compile env failed."
	fi

	tar -xf openEuler_compile_env_${ARCH}-1.0.0.tar.gz -C /
	rm -rf ${chroot_lkp} && mkdir -p ${chroot_lkp}
	cp "/etc/resolv.conf" "${root_path}/etc/"
	cp -a "${LKP_SRC}/"* ${chroot_lkp}
}

create_compile_env()
{
	config_envmaker_repo
	init_compile_env
}
