def main():
    if len(sys.argv) < 3:
        usage()

    sr_path = sys.argv[1]
    action = sys.argv[2]

    if action not in ('print', 'delete', 'move'):
        usage()

    if action == 'move':
        if len(sys.argv) < 4:
            print "error: must specify where to move bad VHDs"
            sys.exit(1)

        bad_vhd_path = sys.argv[3]
        if not os.path.exists(bad_vhd_path):
            os.makedirs(bad_vhd_path)

    bad_leaves = []
    descendents = {}

    for fname in glob.glob(os.path.join(sr_path, "*.vhd")):
        (returncode, stdout, stderr) = execute(
            ['vhd-util', 'query', '-n', fname, '-p'], ok_exit_codes=[0, 22])

        stdout = stdout.strip()

        if stdout.endswith('.vhd'):
            try:
                descendents[stdout].append(fname)
            except __HOLE__:
                descendents[stdout] = [fname]
        elif 'query failed' in stdout:
            bad_leaves.append(fname)

    def walk_vhds(root):
        yield root
        if root in descendents:
            for child in descendents[root]:
                for vhd in walk_vhds(child):
                    yield vhd

    for bad_leaf in bad_leaves:
        for bad_vhd in walk_vhds(bad_leaf):
            print bad_vhd
            if action == "print":
                pass
            elif action == "delete":
                os.unlink(bad_vhd)
            elif action == "move":
                new_path = os.path.join(bad_vhd_path,
                                        os.path.basename(bad_vhd))
                os.rename(bad_vhd, new_path)
            else:
                raise Exception("invalid action %s" % action)
dataset/ETHPy150Open BU-NU-CLOUD-SP16/Trusted-Platform-Module-nova/tools/xenserver/vdi_chain_cleanup.py/main