#!/bin/bash -e
TARGET_ROOTFS_DIR=/home/data/rootfs/rk356x/ubuntu20-lxde/rk3568_ubuntu20_WM
#TARGET_ROOTFS_DIR=/home/data/rootfs/rk356x/ubuntu20-lxde/lxde_ubuntu20_rootfs
#TARGET_ROOTFS_DIR=/home/data/rootfs/rk356x/debian10/rk3568_likong
#TARGET_ROOTFS_DIR=/home/data/rootfs/rk356x/debian11/debian11_5.10
#TARGET_ROOTFS_DIR=/home/data/rootfs/rk356x/debian10/debian_rootfs_jrty
MOUNTPOINT=./temp
ROOTFSIMAGE=rootfs.ext4
OUT=$PWD/tools/linux/Linux_Pack_Firmware/rockdev/Image/

echo Making rootfs!

if [ -e ${ROOTFSIMAGE} ]; then 
	rm ${ROOTFSIMAGE}
fi
if [ -e ${MOUNTPOINT} ]; then 
	rm -r ${MOUNTPOINT}
fi

# Create directories
mkdir ${MOUNTPOINT}
dd if=/dev/zero of=${ROOTFSIMAGE} bs=1M count=0 seek=4200

finish() {
	sudo umount ${MOUNTPOINT} || true
	echo -e "\e[31m MAKE ROOTFS FAILED.\e[0m"
	exit -1
}

echo Format rootfs to ext4
mkfs.ext4 ${ROOTFSIMAGE}

echo Mount rootfs to ${MOUNTPOINT}
sudo mount  ${ROOTFSIMAGE} ${MOUNTPOINT}
trap finish ERR

echo Copy rootfs to ${MOUNTPOINT}
sudo cp -rvfp ${TARGET_ROOTFS_DIR}/*  ${MOUNTPOINT}
sync


echo Umount rootfs
sudo umount ${MOUNTPOINT}

echo Rootfs Image: ${ROOTFSIMAGE}

e2fsck -p -f ${ROOTFSIMAGE}
resize2fs -M ${ROOTFSIMAGE}

#[ ! -d ${OUT} ] && mkdir ${OUT}
cp $ROOTFSIMAGE ${OUT}

unlink $ROOTFSIMAGE
cd ..
