#!/bin/bash
#%stage: block
#

fdupes_s() {
	local _target=""
	local _file=
	fdupes --quiet --noempty --recurse "$@" |
		while read _file
		do
			if test -z "$_target"
			then
				_target="$_file"
			else
				if test -z "$_file"
				then
					_target=""
					continue
				fi
				echo ln -fv "${_target##*/}" "$_file"
			fi
		done
}

# copy daemon manually because it is located in RPM_BUILD_ROOT
mkdir -vp $tmp_mnt/usr/sbin
cp_bin $(type -p guestfsd) $tmp_mnt/usr/sbin
# required for mount.nfs inside the appliance
for i in /etc/netconfig /etc/protocols /etc/rpc /etc/services
do
	cp $i $tmp_mnt$i
done

# Disable ipv6 because host names resolve to ipv4 and ipv6
# Resolver may prefer ipv6 and qemu usernet does only ipv4
echo install ipv6 /bin/true >> $tmp_mnt/etc/modprobe.conf.local

# many guestfish commands need a mount point
# in guestfsd the mount point defaults to /sysroot
mkdir -vp $tmp_mnt/sysroot

# guestfsd tries to bind mount this directory
mkdir -vp $tmp_mnt/selinux

for f in /etc/magic /usr/share/misc/magic*
do
	if test -e $f
	then
		cp -av --parents $f $tmp_mnt/
	fi
done
for d in /usr/share/*augeas*
do
	if test -e $d
	then
		cp -av --parents $d $tmp_mnt/
	fi
done

mkdir -p $tmp_mnt/usr/share/guestfs
if test -n "$LIBGUESTFS_SRC_APPLIANCE_DIR"
then
	for f in $LIBGUESTFS_SRC_APPLIANCE_DIR/*.aug
	do
		if test -e $f
		then
			cp -Lavt $tmp_mnt/usr/share/guestfs $f
		fi
	done
fi
for d in /usr/lib*/gconv
do
	if test -e $d
	then
		cp -avL --parents $d $tmp_mnt/
		fdupes_s $tmp_mnt$d
	fi
done

for t in \
	screen \
	vt100 \
	vt102 \
	linux
do
	ti="`echo /usr/share/terminfo/*/${t}`"
	for f in $ti
	do
		if test -f "${f}"
		then
			cp -av --parents $f $tmp_mnt
		fi
	done
done

# copy needed rules
for rule in \
	95-dm-notify.rules \
	; do
	if [ -f /lib/udev/rules.d/$rule ]; then
		cp /lib/udev/rules.d/$rule $tmp_mnt/lib/udev/rules.d
	elif [ -f /etc/udev/rules.d/$rule ]; then
		cp /etc/udev/rules.d/$rule $tmp_mnt/etc/udev/rules.d
	fi
done

# Need to create the modprobe.conf file to force read-write mode
if modinfo -k $kernel_version ext4 | grep -E '^parm:[[:blank:]]+rw:'
then
	mkdir -vp "${tmp_mnt}/etc/modprobe.d"
	echo "options ext4 rw=1" >> "${tmp_mnt}/etc/modprobe.d/ext4-kmp-rw.conf"
fi

# Bug 674684 - mount-rootfs-and-do-chroot.sh
cat > $tmp_mnt/bin/mount-rootfs-and-do-chroot.sh <<'__EOF__'
#!/bin/bash
# Usage: $0 /dev/sda5
rootfs=$1
mnt=/sysroot
mounts=

if test -b "${rootfs}"
then

	mkdir -v -p "${mnt}"

	if mount -v "${rootfs}" "${mnt}"
	then

		for i in dev dev/pts proc sys selinux
		do
			if test -d /${i} && test -d "${mnt}/${i}" && test "`stat -c %D /`" != "`stat -c %D ${i}`"
			then
				mount -v --bind /${i} "${mnt}/${i}"
			fi
		done

		chroot "${mnt}" su -

		while read b m rest
		do
			case "${m}" in
				${mnt}*)
					mounts="${m} ${mounts}"
				;;
			esac
		done <<-EOF
`
cat < /proc/mounts
`
EOF

		for i in ${mounts}
		do
			umount -v "${i}"
		done

	fi

fi
__EOF__

