#!/usr/bin/python3
# -*- coding: utf-8 -*-

# This file is part of Cockpit.
#
# Copyright (C) 2015 Red Hat, Inc.
#
# Cockpit is free software; you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation; either version 2.1 of the License, or
# (at your option) any later version.
#
# Cockpit is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Cockpit; If not, see <http://www.gnu.org/licenses/>.

import parent
from testlib import *
from storagelib import *

class TestStorage(StorageCase):
    def testUsed(self):
        m = self.machine
        b = self.browser

        self.login_and_go("/storage")
        b.wait_in_text("#drives", "VirtIO")

        m.add_disk("50M", serial="DISK1")
        b.wait_in_text("#drives", "DISK1")
        m.execute("parted -s /dev/disk/by-id/scsi-0QEMU_QEMU_HARDDISK_DISK1 mktable msdos")
        m.execute("parted -s /dev/disk/by-id/scsi-0QEMU_QEMU_HARDDISK_DISK1 mkpart primary ext2 1M 25")
        m.execute("udevadm settle")
        m.execute("echo einszweidrei | cryptsetup luksFormat /dev/disk/by-id/scsi-0QEMU_QEMU_HARDDISK_DISK1-part1")
        m.execute("echo einszweidrei | cryptsetup luksOpen /dev/disk/by-id/scsi-0QEMU_QEMU_HARDDISK_DISK1-part1 dm-test")
        m.execute("udevadm settle")
        m.execute("mke2fs -q -L TEST /dev/mapper/dm-test")
        m.execute("mount /dev/mapper/dm-test /mnt")

        # Now all of /dev/mapper/dm-test, /dev/sda1, and /dev/sda should be 'in use'.

        b.click('tr:contains("DISK1")')
        b.wait_visible("#storage-detail")
        self.content_tab_wait_in_info(2, 1, "Mounted At", "/mnt")

        self.content_tab_action(2, 1, "Format")
        self.dialog_wait_open()
        b.wait_in_text("#dialog", "Proceeding will unmount all filesystems on it.")
        self.dialog_cancel()
        self.dialog_wait_close()

        # Further tear down doesn't work with the old UDisks2
        if self.storaged_is_old_udisks:
            return

        self.content_head_action(1, "Delete")
        self.dialog_wait_open()
        b.wait_in_text("#dialog", "Proceeding will unmount all filesystems on it.")
        self.dialog_cancel()
        self.dialog_wait_close()

        # No go ahead and let the automatic teardown take care of the mount

        b.click('button:contains(Create partition table)')
        self.dialog_wait_open()
        b.wait_in_text("#dialog", "Proceeding will unmount all filesystems on it.")
        self.dialog_apply()
        self.dialog_wait_close()

        self.content_row_wait_in_col(1, 1, "Free Space")

if __name__ == '__main__':
    test_main()
