#!/usr/bin/python3

# 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 storagelib import *
from testlib import *


@nondestructive
class TestStorage(StorageCase):

    def testBasic(self):
        m = self.machine
        b = self.browser

        self.allow_authorize_journal_messages()
        self.login_and_go("/storage", authorized=False)

        b.wait_present("#devices [data-toggle=dropdown]:disabled")

        b.relogin('/storage', authorized=True)
        self.browser.wait_present("#devices [data-toggle=dropdown]:not(:disabled)")

        b.wait_in_text("#drives", "VirtIO")
        b.wait_not_in_text("#drives", "Show all")

        # Add a disk, partition it, format it, and finally remove it.
        disk = self.add_ram_disk()

        b.wait_in_text("#drives", disk)
        b.click('tr:contains("%s")' % disk)
        b.wait_present('#storage-detail')
        self.content_row_wait_in_col(1, 1, "Unrecognized Data")

        def info_field_value(name):
            return b.text('#detail-header label:contains("%s") + div' % name)

        self.assertEqual(self.inode(info_field_value("Device File")), self.inode(disk))

        m.execute('parted -s %s mktable gpt' % disk)
        m.execute('parted -s %s mkpart primary ext2 1M 8M' % disk)
        self.content_row_wait_in_col(1, 1, "Unrecognized Data")
        self.content_tab_wait_in_info(1, 1, "Name", "primary")

        # create file system on the first partition
        # HACK - the block device might disappear briefly when udevd does its BLKRRPART.
        wait(lambda: m.execute('mke2fs %s1' % disk), delay=1, tries=5)
        self.content_row_wait_in_col(1, 1, "ext2 File System")

        b.go("#/")
        b.wait_visible('#storage')
        b.wait_in_text("#drives", disk)
        self.force_remove_disk(disk)
        b.wait_not_in_text("#drives", disk)


if __name__ == '__main__':
    test_main()
