#! /usr/bin/env python

"""
``consistency-invalidate`` reads from the history database
and entered debugged sites into the dynamo server.
Site patterns can also be set, if desired.
"""


__usage__ = '%prog [options]'


import logging

from dynamo_consistency import opts
from dynamo_consistency import history
from dynamo_consistency import summary
from dynamo_consistency.parser import pretty_exe

from dynamo.core.executable import inventory          # pylint: disable=import-error
from dynamo.registry.registry import RegistryDatabase # pylint: disable=import-error


pretty_exe('consistency-invalidate')


if __name__ == '__main__':
    LOG = logging.getLogger(__name__)
    registry = RegistryDatabase()

    # Only get sites that we want to report
    # Match pattern if asked for
    sites = [site for site in summary.get_sites(True)
             if opts.SITE_PATTERN is None or opts.SITE_PATTERN in site]

    for site in sites:
        for lfn in history.missing_files(site):
            lfile = inventory.find_file(lfn)
            if lfile is None:
                # something is wrong
                LOG.warning('Could not find file: %s', lfn)
                continue

            block_replica = lfile.block.find_replica(inventory.sites[site])
            if block_replica is None:
                # the file is not really missing any more
                LOG.warning('Could not find block with %s at %s', lfn, site)
                continue

            block_replica.delete_file(lfile)

            inventory.register_update(block_replica) # pylint: disable=no-member

            # temporary while PhEDEx is in the way
            registry.db.query(
                """
                INSERT INTO `local_invalidations`
                (`site`, `lfn`) VALUES (%s, %s)
                """, site, lfn)

        # Now move them over
        history.missing_files(site, True)
