#!/usr/bin/python
#
# Copyright 2008 Red Hat, Inc. and/or its affiliates.
#
# Licensed to you under 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.  See the files README and
# LICENSE_GPL_v2 which accompany this distribution.
#

import os, sys, getopt
import subprocess
import traceback
import constants
from config import config
config.read(constants.P_VDSM_CONF + 'vdsm.conf')

VDS_CLIENT = constants.EXT_VDSCLIENT
QEMU_IMG = config.get('vars', 'qemuimg')
SSL = config.getboolean('vars', 'ssl')

def ImageVerifier(img):
    if not img:
        img = os.environ.get('hda')

    if not img:
        rc = 0 
    else:
        p = subprocess.Popen([QEMU_IMG, "check", img], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        p.wait()
        rc = p.returncode
        sys.stdout.write(p.stdout.read(1024)+p.stderr.read(1024))
        if rc:
            uuid = os.path.splitext(os.path.basename(img))[0]
            ssl = [[], ['-s']][SSL]
            subprocess.Popen([VDS_CLIENT] + ssl + ['0', 'setImageLegality', uuid, 'ILLEGAL'])
            sys.stderr.write("Image corrupted\n")
    return rc

def main():
    """ Usage: img_verifier
        [-i image] - image to verify
    """
    try:
        img = ''
        opts, args = getopt.getopt(sys.argv[1:], "i:")
        for o,v in opts:
            if o == "-i":
                img = v
    except:
        print main.__doc__
        return 0

    try:
        # if 'recover', mean vdsmd service restarted.
        recover = os.environ.has_key('recover')
        # if 'migDest', mean we are in migration process.
        migDest = os.environ.has_key('migrationDest')
        migSrc = False
        exitMessage = os.environ.get('exitMessage')
        exitCode = os.environ.get('exitCode')
        if exitMessage and exitCode:
            if exitMessage=='Migration succeeded' and exitCode=='0':
                migSrc = True
        # do not run script if: vdsmd restarted or VM migrated
        if not recover and not migDest and not migSrc:
            ret = ImageVerifier(img)
        else:
            print "**** Skipping image validation script"
            return 0
    except:
        print traceback.format_exc()
        ret = -1

    if ret:
        print '**** Image Validation: FAIL'
    else:
        print '**** Image Validation: OK'
    return ret

if __name__ == "__main__":
    sys.exit(main())

