#
# Copyright (c) 2014 Intel, Inc.
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the Free
# Software Foundation; version 2 of the License
#
# This program 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 General Public License
# for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc., 59
# Temple Place - Suite 330, Boston, MA 02111-1307, USA.

import os
import subprocess
import shutil

from mic import msger, rt_util
from mic.plugin import pluginmgr
from mic.pluginbase import ImagerPlugin
from mic.imager.qcow import QcowImageCreator
from mic.utils import errors, runner

class QcowPlugin(ImagerPlugin):
    name = 'qcow'

    @classmethod
    def do_create(cls, args):
        """${cmd_name}: create qcow image
        """

        creatoropts, pkgmgr, recording_pkgs = rt_util.prepare_create(args)

        creator = QcowImageCreator(creatoropts,
                                   pkgmgr)

        if len(recording_pkgs) > 0:
            creator._recording_pkgs = recording_pkgs

        image_names = [creator.name + ".img"]
        image_names.extend(creator.get_image_names())
        cls.check_image_exists(creator.destdir,
                                creator.pack_to,
                                image_names,
                                creatoropts['release'])

        try:
            creator.check_depend_tools()
            creator.mount(None, creatoropts["cachedir"])
            creator.install()
            creator.tpkinstall()
            creator.configure(creatoropts["repomd"])
            creator.copy_kernel()
            creator.create_cpio_image()
            creator.unmount()
            creator.copy_cpio_image()
            creator.package(creatoropts["destdir"])
            creator.create_manifest()

            if creatoropts['release'] is not None:
                creator.release_output(args.ksfile,
                                       creatoropts['destdir'],
                                       creatoropts['release'])
            creator.print_outimage_info()

        except errors.CreatorError:
            raise
        finally:
            creator.cleanup()

        #Run script of --run_script after image created
        if creatoropts['run_script']:
            cmd = creatoropts['run_script']
            try:
                runner.show(cmd)
            except OSError as err:
                msger.warning(str(err))


        msger.info("Finished.")
        return 0

    @classmethod
    def do_chroot(cls, target, cmd=[]):
        pass

    @classmethod
    def do_unpack(cls, srcimg):
        pass
