#!/bin/sh
# This script is used to sync a remote-rootfs directory to local
# disk partition, in order to sync multiple rootfs, we use the
# btrfs as the local disk partition filesystem, for its subvolume
# feature.
#
# Currently, only support NFS format remote-rootfs as the first
# parameter, but easy to add more remote-rootfs format support
# in future if we need.

# eg: lkp-server:/osimage/debian-full-x86_64
source=$1
[ -z "${source}" ] && {
	echo "Parameter is empty."
	exit 1
}

rootfs_name=${source##*/}
# To remove the version info from rootfs's name
# eywa-x86_64-20160714-1 ==> eywa-x86_64
rootfs_name=${rootfs_name%*-[0-9]*-[0-9]}

# eg: /dev/disk/by-id/ata-WDC_WD1002FAEX-00Z3A0_WD-WCATRC577623-part2
# eg: LABEL=LKP-ROOTFS
dest=$2
dest_partition=$(readlink -e $dest)
[ -z "$dest_partition" ] &&
dest_partition=$(blkid | grep ${dest#*=} | cut -d':' -f1)

[ ! -b ${dest_partition} ] && {
	echo "Partition ${dest} can't be found!"
	exit 1
}

fs_type=$(blkid -o value -s TYPE $dest_partition)
[ "${fs_type}" != "btrfs" ] && {
	umount ${dest_partition} 2>/dev/null
	opt_mkfs=
	mkfs.btrfs 2>&1 | grep -q -- --force && opt_mkfs='-f'
	mkfs.btrfs $opt_mkfs -L "LKP-ROOTFS" ${dest_partition} || exit
}

MNT_POINT=${MNT_POINT:-$(cat /proc/mounts | grep -w "$dest_partition" | cut -d' ' -f2)}
if [ -z "$MNT_POINT" ];then
	MNT_POINT="/opt/rootfs"
	mkdir -p $MNT_POINT || exit
	mount ${dest_partition} $MNT_POINT || exit
fi

# for CACHE_DIR
mkdir -p $MNT_POINT/tmp || exit

# create BTRFS subvolume
# the subvolume can be used like:
# mount -o subvol=$rootfs_name $dest_partition /some-path
local_mount_rootfs=$MNT_POINT/$rootfs_name
[ ! -d "$local_mount_rootfs" ] && {
	btrfs subvolume create $local_mount_rootfs || exit
}

# create NFS mount directory
nfs_mount_rootfs=$MNT_POINT/NFS-${rootfs_name}

[ -d ${nfs_mount_rootfs} ] || mkdir -p ${nfs_mount_rootfs} || exit

# mount NFS to local and rsync to destination subvolume
if command -v mount.nfs >/dev/null; then
	NFSMOUNT="mount.nfs"
else
	NFSMOUNT="mount"
fi
$NFSMOUNT -o ro,nolock $source $nfs_mount_rootfs || exit

# do rsync only when remote rootfs is updated
diff $nfs_mount_rootfs/etc/rsync-rootfs-version $local_mount_rootfs/etc/rsync-rootfs-version
if [ $? -eq 0 -a -f $local_mount_rootfs/etc/rsync-rootfs-complete ];then
	echo "rsync-rootfs: $local_mount_rootfs rootfs is up-to-date"
	umount $nfs_mount_rootfs
	exit $?
fi

# delete the completion file
rm -f $local_mount_rootfs/etc/rsync-rootfs-complete

# start rsyncing
rsync -aix --delete $nfs_mount_rootfs/ $local_mount_rootfs || exit

# touch a file to indicate the completion of rsync
touch $local_mount_rootfs/etc/rsync-rootfs-complete

# umount NFS
umount $nfs_mount_rootfs || exit
