#!/usr/bin/python3
#
# group: disabled
# VZ: disabled due to PSBM-152347
#
# Test removing persistent bitmap from backing
#
# Copyright (c) 2021 Virtuozzo International GmbH.
#
# 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; either version 2 of the License, or
# (at your option) any later version.
#
# 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, see <http://www.gnu.org/licenses/>.
#

import subprocess
from contextlib import contextmanager
import iotests
from iotests import log, qemu_img_create, qemu_img, qemu_io


def find_loop_by_file(filepath):
    out = subprocess.run(['losetup', '-l'], stdout=subprocess.PIPE,
                         universal_newlines=True, check=True).stdout
    try:
        line = next(line for line in out.split('\n') if filepath in line)
        return line.split()[0]
    except StopIteration:
        return None


@contextmanager
def loop_device(filepath):
    assert find_loop_by_file(filepath) is None
    subprocess.run(['losetup', '-f', filepath], check=True)
    loopdev = find_loop_by_file(filepath)
    assert loopdev is not None

    try:
        yield loopdev
    finally:
        subprocess.run(['losetup', '-d', loopdev], check=True)


def bitmap_sha256(vm_obj, node, name):
    return vm_obj.qmp('x-debug-block-dirty-bitmap-sha256',
                      node=node, name=name)['return']['sha256']


iotests.script_initialize(supported_fmts=['qcow2'])

disk, raw = iotests.file_path('disk', 'raw')
size = '1M'

assert qemu_img_create('-f', iotests.imgfmt, disk, size).returncode == 0
assert qemu_img_create('-f', 'raw', raw, size).returncode == 0

assert qemu_img('bitmap', '--add', disk, 'bitmap0').returncode == 0
# Just assert that our method of checking bitmaps in the image works.
assert 'bitmaps' in qemu_img('info', disk).stdout

qemu_io('-c', 'write 0 128K', disk)
qemu_io('-c', 'write 500K 100K', disk)

with loop_device(raw) as loop, iotests.VM() as vm:
    vm.add_drive(disk, 'node-name=disk0,file.node-name=file0')
    vm.add_drive_raw(f'driver=host_device,filename={loop},node-name=file1')
    vm.launch()

    # Bitmap is non-empty
    query_block = vm.qmp('query-block')['return']
    assert query_block[0]['inserted']['dirty-bitmaps'][0]['count'] > 0
    h1 = bitmap_sha256(vm, 'disk0', 'bitmap0')

    vm.qmp_log('block-dirty-bitmap-merge', conv_keys=False,
               node='file1', target='123e4567-e89b-12d3-a456-426614174000',
               __vz_push=True,
               bitmaps=[{'node': 'disk0', 'name': 'bitmap0'}])

    vm.qmp_log('block-dirty-bitmap-add', node='disk0', name='test')
    h2 = bitmap_sha256(vm, 'disk0', 'test')
    # Hash of empty bitmap should differ
    assert h1 != h2

    vm.qmp_log('block-dirty-bitmap-merge', conv_keys=False,
               node='disk0', target='test',
               bitmaps=[{'node': 'file1',
                         'name': '123e4567-e89b-12d3-a456-426614174000',
                         '__vz_pull': True}])
    h3 = bitmap_sha256(vm, 'disk0', 'test')
    assert h3 == h1
