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

set -e

. $LKP_SRC/lib/debug.sh
. $LKP_SRC/lib/log.sh

check_params()
{
	log_info "start check params"

	local required_vars=(
		"iso_os"
		"iso_arch"
		"iso_version"
		"NFS_SERVER_HOST"
		"NFS_ROOT_DIR"

		"group_id"
		"VG_NAME"
	)

	for i in "${required_vars[@]}"
	do
		[ -n "$(eval echo \$$i)" ] || die "cannot get value of var: $i"
	done
}

delete_firstboot_cgz()
{
	local cgz_url="http://${INITRD_HTTP_HOST}:${INITRD_HTTP_PORT}/initrd/custom_bootstrap/reboot-after-systemd-logind.cgz"

	local tmp_dir="/tmp/$(basename $cgz_url)_${group_id}"
	rm -rf $tmp_dir && mkdir -p $tmp_dir && cd $tmp_dir

	wget $cgz_url || die "wget cgz failed: $cgz_url"

	gzip -dc reboot-after-systemd-logind.cgz | cpio -id

	[ -d "custom_bootstrap" ] || die "cannot find custom_bootstrap dir after unzip"

	for i in $(find custom_bootstrap/* -not -type d)
	do
		rm -f ${lv_rootfs_mount_point}/${i#custom_bootstrap/}
	done
}

sync_rootfs_to_nfs_server()
{
	# mount nfs rootfs
	local nfs_rootfs_mount_point=/tmp/nfs_rootfs_${group_id}

	mkdir -p ${nfs_rootfs_mount_point}
	mount -t nfs ${NFS_SERVER_HOST}:${NFS_ROOT_DIR}/${iso_os}/${iso_arch}/${iso_version}-iso-${group_id} ${nfs_rootfs_mount_point} || die "mount nfs rootfs failed"

	# activate the lvm
	vgscan --cache
	vgchange -ay || vgchange -ay $VG_NAME

	# mount local logical volume
	local iso_version=${iso_version//-/_}
	local lv_rootfs_mount_point=/tmp/lv_rootfs_${group_id}

	mkdir -p ${lv_rootfs_mount_point}
	mount /dev/mapper/${VG_NAME}-${iso_os}_${iso_arch}_${iso_version}_${group_id} ${lv_rootfs_mount_point} || die "mount lv rootfs failed"

	# delete cgz for firstboot reboot
	delete_firstboot_cgz

	# sync rootfs
	cp -a ${lv_rootfs_mount_point}/. ${nfs_rootfs_mount_point} || die "copy out rootfs failed"

	# umount nfs rootfs
	cd / && umount $nfs_rootfs_mount_point || log_warn "umount failed: nfs_rootfs_mount_point"

	# umount local logical volume
	umount $lv_rootfs_mount_point || log_warn "umount failed: $lv_rootfs_mount_point"

	lvchange --permission r /dev/mapper/${VG_NAME}-${iso_os}_${iso_arch}_${iso_version}_${group_id} ||
		die "change logical volume permission to readonly failed:/dev/mapper/${VG_NAME}-${iso_os}_${iso_arch}_${iso_version}_${group_id}"
}

main()
{
	check_params

	sync_rootfs_to_nfs_server
}

main
