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

import parent
from common import testinfra
from common import vmimages
from common import vmmanage

if __name__ == "__main__":
    parser = argparse.ArgumentParser(
            description='Prepare testing environment, download images and build and install cockpit',
            formatter_class=argparse.ArgumentDefaultsHelpFormatter
        )
    parser.add_argument('-v', '--verbose', action='store_true', help='Display verbose progress details')
    parser.add_argument('-n', '--noinstall', action='store_true', help='Do not install cockpit to base image')
    parser.add_argument('-f', '--force', action='store_true', help='Force update of images')
    parser.add_argument('image', nargs='?', default=testinfra.DEFAULT_IMAGE, help='The image to use')
    args = parser.parse_args()

    test_os = args.image
    build_os = vmmanage.get_build_image(test_os)

    os.system(os.path.join(testinfra.TEST_DIR,"vm-reset"))
    try:
        vmimages.download_images([build_os], args.force, [])
    except Exception as e:
        print "unable to download all necessary images", e
        sys.exit(1)

    retvalue=0
    if args.noinstall:
        print "Not installing cockpit to base image"
    else:
        try:
            vmmanage.build_and_install(test_os, build_os, {"verbose":args.verbose, "force": args.force})
        except Exception as e:
            print e
            retvalue=2
        if os.environ.has_key("TEST_ATTACHMENTS"):
            attachement_dir = os.environ["TEST_ATTACHMENTS"]
            try:
                os.makedirs(os.path.join(attachement_dir, "build-results"))
            except Exception as e:
                pass
            for cpfile in glob.glob(os.path.join(testinfra.TEST_DIR,"tmp","build-results","*.log")):
                shutil.copy(cpfile, os.path.join(attachement_dir ,"build-results"))
    sys.exit(retvalue)
