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

# This file is part of Cockpit.
#
# Copyright (C) 2013 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 *
import os

def readFile(name):
    content = ''
    if os.path.exists(name):
        with open(name, 'r') as f:
            content = f.read().replace('\n', '')
    return content

# If this test fails to run, the host machine needs:
# echo "options kvm-intel nested=1" > /etc/modprobe.d/kvm-intel.conf
# rmmod kvm-intel && modprobe kvm-intel || true

@skipImage("Atomic cannot run virtual machines", "fedora-atomic", "rhel-atomic", "continuous-atomic")
class TestMachines(MachineCase):
    vm1_name="subVmTest1"
    vm1_id="#vm-{0}".format(vm1_name)
    vm1_img = "/var/lib/libvirt/images/{0}.img".format(vm1_name)

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

        # Ensure everything has started correctly
        m.execute("systemctl start libvirtd")
        # Wait until we can get a list of domains
        wait(lambda: m.execute("virsh list"))
        # Wait for the network 'default' to become active
        wait(lambda: m.execute(command="virsh net-info default | grep Active"))

        self.login_and_go("/machines")
        b.wait_in_text("body", "No VM is running or defined on this host")

        m.execute("qemu-img create -f qcow2 {0} 1G".format(self.vm1_img))
        m.execute("virt-install --cpu host -r 128 --pxe --force --nographics --noautoconsole --disk path={0},size=1,format=qcow2 -n {1} || true".format(self.vm1_img, self.vm1_name))

    def testBasic(self):
        self.envSetup()

        b = self.browser
        m = self.machine

        # state == 'running' is expected, but can be 'paused' if the VM creation fails. Anyway, the VM shall be listed at least
        state = m.execute("virsh domstate {0}".format(self.vm1_name)).strip()
        # debug info: machine state
        m.message("state: '{0}'".format(state))
        self.assertIn(state, ["running", "paused"], "Test environment failed to set up - testing VM failed to start")

        b.wait_in_text("body", "Virtual Machines")
        b.wait_in_text("tbody tr th", self.vm1_name) # is VM name listed?

        b.click("tbody tr th") # click on the row header
        b.wait_present("{0}-state".format(self.vm1_id))
        b.wait_in_text("{0}-state".format(self.vm1_id), state) # running or paused
        b.wait_present("{0}-vcpus".format(self.vm1_id))
        b.wait_in_text("{0}-vcpus".format(self.vm1_id), "1")

        if state == "running":
            b.click("{0}-off-caret".format(self.vm1_id))
            b.wait_visible("{0}-forceOff".format(self.vm1_id))
            b.click("{0}-forceOff".format(self.vm1_id))
            b.wait_in_text("{0}-state".format(self.vm1_id), "shut off")
        else:
            print "WARNING: Test VM creation failed, virt-install finished in 'paused' state. Skipping the 'shut down scenario'"

if __name__ == '__main__':
    test_main()
