#!/usr/bin/bash
set -eu

# Derived from Dracut TEST-21-OVERLAYFS

# shellcheck source=debian/tests/prepare-dracut
. debian/tests/prepare-dracut

# shellcheck disable=SC2034
TEST_DESCRIPTION="Test overlayfs module with persistent device overlay"

# Uncomment this to debug failures
#DEBUGFAIL="rd.debug rd.shell"

client_run() {
    local test_name="$1"
    shift
    local client_opts="$*"

    client_test_start "$test_name"

    declare -a disk_args=()
    qemu_add_drive disk_args "$TESTDIR"/root.img root
    qemu_add_drive disk_args "$TESTDIR"/overlay.img overlay

    "$testdir"/run-qemu -nic none \
        "${disk_args[@]}" \
        -append "$TEST_KERNEL_CMDLINE root=LABEL=dracut $client_opts" \
        -initrd "$TESTDIR"/initramfs.testing
    check_qemu_log

    client_test_end
}

test_run() {
    local overlay_uuid
    overlay_uuid=$(blkid -s UUID -o value "$TESTDIR"/overlay.img)

    client_run "overlayroot=tmpfs" "overlayroot=tmpfs test.expect=tmpfs"
    client_run "overlayroot=LABEL" "overlayroot=LABEL=OVERLAY test.expect=device"
    client_run "overlayroot=UUID" "overlayroot=UUID=$overlay_uuid test.expect=device"
    client_run "overlayroot=/dev" \
        "overlayroot=/dev/disk/by-id/scsi-0QEMU_QEMU_HARDDISK_overlay test.expect=device"
}

test_setup() {
    build_client_rootfs "$TESTDIR/rootfs"
    cp debian/tests/overlayroot-dracut-assertion.sh "$TESTDIR/rootfs/assertion.sh"
    binaries=$(sed -n "s/^# required binaries: \(.*\)/\1/p" debian/tests/overlayroot-dracut-assertion.sh)
    # shellcheck disable=SC2086
    inst_multiple $binaries
    build_ext4_image "$TESTDIR/rootfs" "$TESTDIR"/root.img dracut

    rm -f "$TESTDIR"/overlay.img
    truncate -s 32M "$TESTDIR"/overlay.img
    mkfs.ext4 -q -L OVERLAY "$TESTDIR"/overlay.img

    test_dracut
}

# shellcheck disable=SC1090
. "$testdir"/test-functions
