#!/usr/bin/python

'''
The healthcheck service - a thin wrapper around the evaluation class
providing the interface to MCP
'''

import errno
import fcntl
import isi.config.mcp as mcp
import logging
import logging.handlers
import os
import shutil

from isi.healthcheck.constants import BASE_DIR
from isi.healthcheck.check import Check
from isi.healthcheck.evaluation import Evaluation

LOG = logging.getLogger(__name__)
LOG.addHandler(logging.handlers.SysLogHandler())
LOG.setLevel(logging.ERROR)

def ensure_directory_exists(path):
    '''
    Ensure that the specified directory exists
    '''
    if not os.path.isdir(path):
        try:
            os.makedirs(path)
        except OSError as err:
            if err.errno == errno.EEXIST:
                pass
            raise

    # Create the evaluation request queue directory
def initialise():
    '''
    Ensure that essential directories and files exist under BASE_DIR
    '''
    checklist_dir = os.path.join(BASE_DIR, 'checklists')
    working_flag = os.path.join(BASE_DIR, 'checklists_working')
    done_flag = os.path.join(BASE_DIR, 'checklists_installed')

    if os.path.exists(done_flag):
        # Already installed nothing to do
        return

    ensure_directory_exists(checklist_dir);
    ensure_directory_exists(os.path.join(BASE_DIR, 'evaluations/current'))

    # No done file - there's work to be done, if we get the lock then
    # we're doing it otherwise another node has it in hand
    lock_fh = open(working_flag, 'a+')
    try:
        fcntl.lockf(lock_fh, fcntl.LOCK_EX | fcntl.LOCK_NB)
    except IOError as exc:
        if exc.errno == errno.EAGAIN:
            lock_fh.close()
        else:
            raise
        return


    # Copy over the distributed checklists
    src_dir = '/usr/libexec/isilon/checklists'
    for checklist in os.listdir(src_dir):
        checklist_path = os.path.join(src_dir, checklist)
        if os.path.isfile(checklist_path):
            shutil.copy(checklist_path, checklist_dir)

    # Touch the done flag, remove the working flag and release the lock
    open(done_flag, 'a+').close()
    os.remove(working_flag)
    fcntl.lockf(lock_fh, fcntl.LOCK_UN)
    lock_fh.close()

def main():
    '''
    Make sure the directories and checklists exist
    Run evaluations until there are none left then disable the service
    '''
    initialise()
    Check.load()
    eval_name = Evaluation.next_evaluation()
    while eval_name:
        evaluation = None
        try:
            evaluation = Evaluation(eval_name)
            evaluation.run()
        except Exception as err:  #pylint: disable=W0703
            LOG.error("Evaluation of %s failed with: %s", eval_name, str(err))
            path = os.path.join(Evaluation.request_dir, eval_name)
            if os.path.exists(path):
                os.remove(path)
        eval_name = Evaluation.next_evaluation()

    mcp.mcpconfig().disable('isi_healthcheck')

if __name__ == "__main__":
    main()
