#!/sbin/openrc-run

depend()
{
	after dev
	before docker
}

start()
{
	ebegin "Configuring host block device"

	# We are being specific with Azure for now.  Otherwise the subshell
	# below will reference /dev/sdb, which is Azure's "local resource disk"
	# (see
	# https://blogs.msdn.microsoft.com/mast/2013/12/06/understanding-the-temporary-drive-on-windows-azure-virtual-machines/).
	#
	# Since attempting to format swap on that disk will cause Azure VHD
	# validation to fail, we default to using /dev/sda.  requirements
	# including not allowing swap partitions.
	#
	# IMPORTANT: If this, or the root device (/dev/sda1) changes in the
	# syslinux / bootloader config for Azure, they will need to be updated
	# in parallel.
	if [ "$(mobyplatform)" = "azure" ]
	then
		DEV="sda"
	else
		DEV="$(find /dev -maxdepth 1 -type b ! -name 'loop*' | grep -v '[0-9]$' | sed 's@.*/dev/@@' | sort | head -1 )"
	fi

	[ -z "${DEV}" ] && exit 1

	DRIVE="/dev/${DEV}"

	if fdisk -l "${DRIVE}" | grep -q "doesn't contain a valid partition table"
	then
		ERASE_DISKS="${DRIVE}" setup-disk -m data "${DRIVE}"
		blockdev --rereadpt "${DRIVE}" 2> /dev/null
	else
		SWAP=$(fdisk -l "${DRIVE}" | grep 'Linux swap' | head -1 | awk '{print $1}')
		DATA=$(fdisk -l "${DRIVE}" | grep 'Linux$' | head -1 | awk '{print $1}')
		if [ -z "$DATA" ]
		then
			ERASE_DISKS="${DRIVE}" setup-disk -m data ${DRIVE}
			blockdev --rereadpt "${DRIVE}" 2> /dev/null
		else
			( mount "${DATA}" /var && ([ -z "${SWAP}" ] || swapon "${SWAP}") ) || \
			  ( ERASE_DISKS="${DRIVE}" setup-disk -m data ${DRIVE}; blockdev --rereadpt ${DRIVE} 2> /dev/null )
		fi
		# boot2docker compat, has /var and /tmp on partition
		[ -d /var/var/lib/boot2docker/ ] && mount --bind /var/var /var
	fi

	mount | grep -q "${DEV}. on /var type"

	eend $? "Failed to mount block device"
}
