#!/usr/bin/python3
#
# Copyright (C) 2026 Red Hat, Inc.
# SPDX-License-Identifier: LGPL-2.1-or-later

from anacondalib import VirtInstallMachineCase
from installer import Installer
from review import Review
from storage import EFI_PARTITION_DEFAULT_SIZE, EFI_PARTITION_DEFAULT_SIZE_MB, Storage
from testlib import nondestructive, test_main  # pylint: disable=import-error


@nondestructive
class TestStorageMountPointsStratis(VirtInstallMachineCase):
    def _testStratis_partition_disk(self):
        m = self.machine
        b = self.browser
        s = Storage(b, m)

        disk = "/dev/vda"
        poolname = "fedorapool"

        s.partition_disk(disk, [(EFI_PARTITION_DEFAULT_SIZE, "efi"), ("1GiB", "ext4"), ("", None)])
        m.execute(f"""
        stratis pool create --no-overprovision {poolname} {disk}3
        stratis filesystem create --size 5GiB {poolname} root
        stratis filesystem create --size 5GiB {poolname} home
        """,
        environment={"STRATIS_DBUS_TIMEOUT": "360000"})

        self.addCleanup(
            lambda: m.execute(f"""
            stratis pool stop --name {poolname} || true
            """, timeout=90)
        )

    def testStratis(self):
        """
        Description:
            Test 'Mount point mapping' screen with Stratis

        Expected results:
            - The mount point mapping screen should show the Stratis volumes
            - The review screen should show the correct mountpoints and devices
        """
        b = self.browser
        m = self.machine
        i = Installer(b, m, scenario="mount-point-mapping")
        s = Storage(b, m)
        r = Review(b, m)

        poolname = "fedorapool"
        dev = "vda"
        i.open()
        i.reach(i.steps.INSTALLATION_METHOD)

        s.select_mountpoint([(dev, True)])

        # verify gathered requests
        # root partition is not auto-mapped
        s.check_mountpoint_row(1, "/", "Select a device", True)
        s.check_mountpoint_row(2, "/boot/efi", "Select a device", False)
        s.check_mountpoint_row(3, "/boot", "Select a device", False)

        s.select_mountpoint_row_device(1, f"{poolname}/root")
        s.check_mountpoint_row(1, "/", f"{poolname}/root", True, "stratis xfs")

        s.select_mountpoint_row_device(2, f"{dev}1")
        s.check_mountpoint_row(2, "/boot/efi", f"{dev}1", False, "EFI System Partition")

        s.select_mountpoint_row_device(3, f"{dev}2")
        s.check_mountpoint_row(3, "/boot", f"{dev}2", False, "ext4")

        s.add_mountpoint_row()
        s.select_mountpoint_row_device(4, f"{poolname}/home")
        s.select_mountpoint_row_mountpoint(4, "/home")
        s.check_mountpoint_row(4, "/home", f"{poolname}/home", False, "stratis xfs")

        # Toggle reformat option
        s.select_mountpoint_row_reformat(3)
        s.check_mountpoint_row_reformat(3, True)

        i.reach(i.steps.REVIEW)

        # verify review screen
        r.check_disk(dev, "16.1 GB vda (Virtio Block Device)")

        r.check_disk_row(dev, "/boot/efi", "vda1", EFI_PARTITION_DEFAULT_SIZE_MB, False)
        r.check_disk_row(dev, "/boot", "vda2", "1.07 GB", True, "ext4")
        r.check_disk_row(dev, "/", "vda3, Stratis", "5.37 GB", True, "stratis xfs")
        r.check_disk_row(dev, "/home", "vda3, Stratis", "5.37 GB", False)

    def _testEncryptedUnlockStratis_partition_disk(self):
        m = self.machine
        b = self.browser
        s = Storage(b, m)

        disk = "/dev/vda"
        poolname = "fedorapool"

        s.partition_disk(disk, [(EFI_PARTITION_DEFAULT_SIZE, "efi"), ("1GiB", "ext4"), ("", None)])
        m.execute(f"""
        echo -n "einszweidrei" > /tmp/stratis-key-file
        stratis key set --keyfile-path /tmp/stratis-key-file stratiskeyring
        stratis pool create --no-overprovision --key-desc stratiskeyring {poolname} {disk}3
        stratis filesystem create --size 10GiB {poolname} root
        """,
        environment={"STRATIS_DBUS_TIMEOUT": "360000"})

        self.addCleanup(
            lambda: m.execute(f"""
            rm /tmp/stratis-key-file || true
            stratis key unset stratiskeyring || true
            stratis pool stop --name {poolname} || true
            """, timeout=90)
        )

    def testEncryptedUnlockStratis(self):
        """
        Description:
            Test that the installer can handle encrypted Stratis pools

        Expected results:
            - The 'Unlock' dialog is available for unlocking the partitions before entering the mount point mapping
            - The user can unlock the disk using a passphrase
            - The user can select the unlocked devices in the mount point mapping
              table.
            - The review screen shows the correct mountpoints and devices
        """
        b = self.browser
        m = self.machine
        i = Installer(b, m)
        s = Storage(b, m)
        r = Review(b, m)

        dev = "vda"
        poolname = "fedorapool"

        i.open()
        i.reach(i.steps.INSTALLATION_METHOD)

        # Unlock the stratis pool device
        s.unlock_all_encrypted()
        s.unlock_device("einszweidrei", ["STRATIS-fedorapool"], ["STRATIS-fedorapool"])

        s.select_mountpoint([(dev, True)])

        # Select the mountpoints
        s.select_mountpoint_row_device(1, f"{poolname}/root")
        s.select_mountpoint_row_device(2, f"{dev}1")
        s.select_mountpoint_row_device(3, f"{dev}2")

        # Verify the review page
        i.reach(i.steps.REVIEW)
        r.check_disk_row(dev, "/boot/efi", "vda1", EFI_PARTITION_DEFAULT_SIZE_MB, False)
        r.check_disk_row(dev, "/boot", "vda2", "1.07 GB", False)
        r.check_disk_row(dev, "/", "vda3, Stratis", "10.7 GB", True, "stratis xfs", True)


if __name__ == '__main__':
    test_main()
