
from __future__ import absolute_import

import os
from collections import namedtuple
from vdsm.common.cmdutils import CommandPath
from vdsm.storage.misc import execCmd

ScanOutput = namedtuple(
    'ScanOutput',
    ['partitionName', 'partitionStartBytes', 'partitionAlignment',
     'alignmentScanResult', 'alignmentScanExplanation'])

_virtAlignmentScan = CommandPath("virt-alignment-scan",
                                 )


class VirtAlignError(Exception):
    pass


def runScanArgs(*args):
    cmd = [_virtAlignmentScan.cmd]
    cmd.extend(args)
    env = os.environ.copy()
    env['LIBGUESTFS_BACKEND'] = 'direct'
    return execCmd(cmd, env=env)


def scanImage(image_path):
    image_path = image_path.strip()
    rc, out, err = runScanArgs('--add', image_path)
    if rc == 0:
        pass
    elif rc == 1:
        raise VirtAlignError("An error scanning the disk image "
                             "or guest:\n%s" % err)
    elif rc == 2:
        pass
    elif rc == 3:
        pass
    else:
        raise ValueError("Unknown return code from "
                         "virt-alignment-scan: %d" % rc)
    outList = []
    for line in out:
        line = line.split(None, 3)
        outList.append(ScanOutput(partName, partStart, partAlignment,
                                  scanResult, scanExplanation))
    return outList
