#
# 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 shutil

from mic.imager.loop import LoopImageCreator
from mic.utils import errors, fs_related, runner

class QcowImageCreator(LoopImageCreator):
    img_format = 'qcow'

    def __init__(self, creatoropts=None, pkgmgr=None):
        LoopImageCreator.__init__(self, creatoropts, pkgmgr)
        self.cmd_qemuimg = 'qemu-img'

    def _stage_final_image(self):
        try:
            self.cmd_qemuimg = fs_related.find_binary_path('qemu-img')
        except errors.CreatorError:
            return LoopImageCreator._stage_final_image(self)

        self._resparse()

        imgfile = None
        for item in self._instloops:
            if item['mountpoint'] == '/':
                if item['fstype'] == "ext4":
                    runner.show('/sbin/tune2fs -O ^huge_file,extents,uninit_bg %s'
                                % imgfile)
                self.image_files.setdefault('partitions', {}).update(
                         {item['mountpoint']: item['label']})
                imgfile = os.path.join(self._imgdir, item['name'])

        if imgfile:
            qemuimage = imgfile + ".x86"
            runner.show("%s convert -O qcow2 %s %s"
                        % (self.cmd_qemuimg, imgfile, qemuimage))
            os.unlink(imgfile)
            os.rename(qemuimage, imgfile)

        for item in os.listdir(self._imgdir):
            shutil.move(os.path.join(self._imgdir, item),
                        os.path.join(self._outdir, item))
