#!/bin/sh

type getarg > /dev/null 2>&1 || . /lib/dracut-lib.sh

# This is intentionally kept in addition to the udev/initqueue finished hook:
# the initqueue hook is event driven, while this pre-mount hook is the last
# line of defence directly before root is mounted.
_rootdev="${1:-/dev/root}"
_wait="$(getarg rd.btrfs.wait=)"
: "${_wait:=120}"

info "PW: pre-mount: call btrfs device scan..."
btrfs device scan > /dev/null 2>&1
btrfs device scan -d > /dev/null 2>&1

_i=0
while true
do
    info "PW: pre-mount: call btrfs device ready for ${_rootdev}..."
    if [ -e "${_rootdev}" ] && btrfs device ready "${_rootdev}" > /dev/null 2>&1; then
        info "PW: pre-mount: btrfs ready!"
        break
    fi

    _i=$((_i + 1))
    if [ "${_wait}" != "0" ] && [ "${_i}" -ge "${_wait}" ]; then
        warn "PW: pre-mount: btrfs not ready after ${_wait}s; continuing anyway"
        break
    fi
    sleep 1
done
