#!/usr/bin/env python
# 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 argparse
import os
import subprocess
import sys

from common import testvm
from common import testinfra

BASE = os.path.dirname(__file__)

parser = argparse.ArgumentParser(description='Run a test machine')
parser.add_argument('-v', '--verbose', action='store_true', help='Display verbose details')
parser.add_argument('-m', '--maintain', action='store_true', help='Changes are permanent')
parser.add_argument('-M', '--memory', default=None, type=int, help='Memory (in MiB) of the target machine')
parser.add_argument('-C', '--cpus', default=None, type=int, help='Number of cpus in the target machine')

parser.add_argument('image', nargs='?', default=testinfra.DEFAULT_IMAGE, help='The image to run')
args = parser.parse_args()

try:
    os.chdir(BASE)
    machine = testvm.VirtMachine(verbose=args.verbose, image=args.image)

    # Hack to make things easier for users who don't know about kubeconfig
    if args.image == 'openshift':
        kubeconfig = os.path.join(os.path.expanduser("~"), ".kube", "config")
        if not os.path.lexists(kubeconfig):
            d = os.path.dirname(kubeconfig)
            src = os.path.abspath(os.path.join("verify", "files", "openshift.kubeconfig"))
            if not os.path.exists(d):
                os.makedirs(d)
            sys.stderr.write("vm-run: linking kubeconfig into ~/.kube/config\n")
            os.symlink(src, kubeconfig)

    # Check that things are configured
    with open(os.devnull, 'w') as fp:
        if subprocess.call(["ip", "address", "show", "dev", "cockpit1"], stdout=fp, stderr=fp) != 0:
            raise Exception("vm-run: please run: sudo {0}/vm-prep".format(BASE))

    # Check that image is downloaded
    if not os.path.exists(machine.image_base):
        ret = subprocess.call(["./vm-download", args.image])
        if ret != 0:
            sys.exit(ret)

    machine.qemu_console(maintain=args.maintain,
                         memory_mb=args.memory,
                         cpus=args.cpus)
except testvm.Failure, ex:
    print >> sys.stderr, "vm-run:", ex
    sys.exit(1)
