#!/usr/bin/python
#
# This file is part of Cockpit.
#
# Copyright (C) 2016 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 os
import unittest
import time

import parent
from testlib import *

def wait_oc(machine):
    i = 0
    while True:
        try:
            machine.execute("oc status")
            break
        except:
            if i > 20:
                raise
            i = i + 1
            time.sleep(1)

@unittest.skipIf("rhel-7" == os.environ.get("TEST_OS", ""), "Skipping check-registry on rhel-7.")
@unittest.skipIf("debian" in os.environ.get("TEST_OS", ""), "No kubernetes on Debian (yet).")
class TestRegistry(MachineCase):
    def setUp(self):
        super(TestRegistry, self).setUp()

        # Start openshift machine
        self.openshift = self.new_machine(image="openshift")
        self.openshift.start()
        self.openshift.wait_boot()

        # Sync over the kube config file
        tmpfile = os.path.join(self.tmpdir, "config")
        self.openshift.download("/root/.kube/config", tmpfile)
        with open(tmpfile, "r") as f:
            self.machine.execute("mkdir -p /home/admin/.kube && cat > /home/admin/.kube/config", input=f.read())
        wait_oc(self.openshift)

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

        self.login_and_go("/registry")
        b.wait_present(".dashboard-summary")

        b.wait_in_text(".card-pf-wide.dashboard-images", "default/busybox")
        b.wait_in_text(".card-pf-wide.dashboard-images", "marmalade/busybee")
        b.wait_in_text(".card-pf-wide.dashboard-images", "marmalade/juggs")
        b.wait_in_text(".card-pf-wide.dashboard-images", "marmalade/origin")

        # Lets navigate to an image stream
        b.click("a[href='#/images/marmalade/busybee']")
        b.wait_in_text(".content-filter h3", "marmalade/busybee")
        b.click("tbody[data-id='marmalade/busybee:0.x'] tr td span.image-tag")
        b.wait_present(".listing-head h3")
        b.wait_in_text(".listing-head h3", "marmalade/busybee:0.x")

if __name__ == '__main__':
    test_main()
