#!/bin/bash
# product "openEuler"
# version "22.09"
# release ""
# repo_url "repo url address"
# upload_image_dir
. $LKP_SRC/lib/upload.sh

set -e

function make_qcow2_image()
{
	ARCH="$(uname -m)"
	RESULT_HMI="/result/virtual_machine/"
	dest_dir="${upload_image_dir}/virtual_machine_img/${ARCH}/"
	if [ -n "${release}" ];then
		VM_IMAGE_NAME="${product}-${version}-${release}-${ARCH}.qcow2"
	else
		VM_IMAGE_NAME="${product}-${version}-${ARCH}.qcow2"
	fi
	[ -d "${RESULT_HMI}" ] && rm -rf "${RESULT_HMI}"
	mkdir -p "${RESULT_HMI}"

	yum clean all -c "${yum_conf}"
	yum install -y qemu-img bc sudo parted dosfstools e2fsprogs xz -c "${yum_conf}"
	if [ $? -ne 0 ];then
		echo "[ERROR] install rpm failed"
		exit 1
	fi

	rm -rf CreateImage
	git clone https://gitee.com/openeuler/CreateImage.git
	if [ $? -ne 0 ];then
		echo "[ERROR] git clone CreateImage failed"
		exit 1
	fi
	sed -i '/#disbale other repos/i \cp /etc/resolv.conf ${TARGET_ROOT}/etc/' CreateImage/hooks/root.d/01-create-root
	sed -i '/most reliable/i \rm -f ${TARGET_ROOT}/etc/resolv.conf' CreateImage/hooks/root.d/01-create-root
	rm -rf /usr/share/CreateImage && mkdir -p /usr/share/CreateImage
	cp CreateImage/bin/* /usr/bin/
	cp -a CreateImage/lib CreateImage/hooks CreateImage/config /usr/share/CreateImage
	rm -rf CreateImage

	cd "${RESULT_HMI}"
	set +e
	chmod 755 /usr/bin/create-image
	create-image -r "${repo_url}"
	mv system.img "${product}"-hmi.raw
	qemu-img convert "${product}"-hmi.raw -O qcow2 "${VM_IMAGE_NAME}"
	local ret_value=$?
	local counter=0
	while [ "${ret_value}" != 0 ]
	do
		qemu-img convert -f raw -O qcow2 "${product}-hmi.raw" "${VM_IMAGE_NAME}"
		ret_value=$?
		counter="$(expr $counter + 1)"
		if [ "${counter}" -gt 3 ]; then
			echo "[ERROR] qemu-img convert failed"
			exit 1
		fi
	done
	echo "[INFO] qemu-img convert success"

	xz -T 0 -9 --lzma2=dict=8MiB "${VM_IMAGE_NAME}"
	cd "${RESULT_HMI}"
	HMI_QCOW2="$(ls *.qcow2.xz)"
	sha256sum "${HMI_QCOW2}" > "${HMI_QCOW2}.sha256sum"
	upload_one_curl "${HMI_QCOW2}" "${dest_dir}"
	upload_one_curl "${HMI_QCOW2}.sha256sum" "${dest_dir}"
	echo "[INFO] make qcow2 image success"
}


make_qcow2_image
