# vim: set ft=sh:

run_hook() {
    if [[ -n "${ip}" && -n "${hyperiso_nbd_srv}" ]]; then

        hyperiso_nbd_srv=$(eval echo ${hyperiso_nbd_srv})
        [[ -z "${hyperiso_nbd_name}" ]] && hyperiso_nbd_name="hyperiso"

        mount_handler="hyperiso_pxe_nbd_mount_handler"
    fi
}

hyperiso_pxe_nbd_mount_handler () {
    newroot="${1}"

    # Module autoloading like with loop devices does not work, doing manually...
    modprobe nbd 2> /dev/null

    msg ":: Waiting for boot device..."
    while ! poll_device /dev/nbd0 30; do
        echo "ERROR: boot device didn't show up after 30 seconds..."
        echo "   Falling back to interactive prompt"
        echo "   You can try to fix the problem manually, log out when you are finished"
        launch_interactive_shell
    done

    msg ":: Setup NBD from ${hyperiso_nbd_srv} at /dev/nbd0"
    nbd-client ${hyperiso_nbd_srv} -N ${hyperiso_nbd_name} /dev/nbd0

    if [[ "${copytoram}" != "n" ]]; then
        copytoram="y"
    fi

    hyperisodevice=/dev/nbd0

    hyperiso_mount_handler ${newroot}

    msg ":: Disconnect NBD from ${hyperiso_nbd_srv} at /dev/nbd0"
    nbd-client -d /dev/nbd0
}
