#!/bin/ash
# uovmount - overlayfs package (ovpkg) unmount script

# Quit if we are not mounted
STATUS=`cat /tmp/ovpkg/status`
if [ $STATUS -eq 0 ]; then
        echo "overlay packages not mounted"
        exit 1
fi

# Unmount overlay dirs in rootfs
for dir in /overlay/*; do
	if [ -d "${dir}" ]; then
		CHK_ROOT_DIR=`echo $dir | sed 's/.*\///'`
		echo "Unmounting overlay: $CHK_ROOT_DIR"
		umount /${CHK_ROOT_DIR}
	fi
done

# Get count of mounts to /overlay
OVCOUNT=`cat /proc/mounts | grep "/overlay" | wc -l`
if [ $OVCOUNT -gt 0 ]; then
	echo "Unmounting /overlay $OVCOUNT times"
fi

# Unmount /overlay OVCOUNT times
COUNTER=0
while [ $COUNTER -lt $OVCOUNT ]; do
	let COUNTER=COUNTER+1
	echo "Unmounting /overlay $COUNTER"
	umount /overlay
done

# Unmount squashfs packages from tmp dir and remove dirs
for dir in /tmp/ovpkg/packages/*; do
	if [ -d "${dir}" ]; then
		echo "Unmounting squashfs: $dir"
		umount ${dir}
		rm -rf ${dir}
	fi
done

# Write status 1=mounted 0=not mounted
echo 0 > /tmp/ovpkg/status
