#!/usr/bin/env python
"""
Copyright (c) 2019 by Cisco Systems, Inc.
All rights reserved.

"""
"""Reads the PNP log files and syslogs it to the remote server """

import os
import select
import logging
import logging.handlers
import syslog
import time
import pnp.infra.utils.pnp_file_paths as files

"""
This script will install a syslog handler on the logger object. It'll read the
logs from the various PNP log files and log them as errors to the syslog if a
valid syslog server is configured.

The script will read the PNP logs till end of file, syslog them, keep track of
the last line/offset that was logged so that it can resume logging from there
on the next iteration

"""

""" Install the syslog handler to the logger object"""
logger = logging.getLogger(__name__)
handler = logging.handlers.SysLogHandler('/dev/log', facility=syslog.LOG_KERN)
handler.setLevel(logging.DEBUG)
logger.addHandler(handler)

""" Read the various PNP log files. These logs files are setup by the PNP
    agent through the constants and infra python files
"""
log_path = {}
log_path['log'] = files.filepaths['log']['pnp']
log_path['err'] = files.filepaths['log']['error']
log_path['no_hup'] = files.filepaths['log']['nohup']
keys = list(log_path.keys())
seek_pos = {}
seek_pos['log'] = 0
seek_pos['err'] = 0
seek_pos['no_hup'] = 0

logger.error("Log: %s, Error: %s & Nohup: %s" % (log_path['log'],
                                    log_path['err'], log_path['no_hup']))
while True:
    """ Log only if the syslog server is configured """
    if os.path.isfile("/tmp/remote_syslog_conf"):
        for i in range(0, len(keys)):
            try:
                fd = open(log_path[keys[i]], "r")
            except IOError as e:
                logger.info("Unable to open File (%s): Error (%s)" %(log_path[keys[i]], e.strerror))
                continue

            logger.debug("Fds %r" %(fd))
            logger.debug("seek_pos for fd %d.%d" %(i, seek_pos[keys[i]]))
            try:
                """ Start from the beginning if the PNP log file was
                    over-written by the PNP agent
                """
                if os.fstat(fd.fileno()).st_size < seek_pos[keys[i]]:
                    seek_pos[keys[i]] = 0
                fd.seek(seek_pos[keys[i]])
                for line in fd:
                    logger.error (line)
                    seek_pos[keys[i]] = seek_pos[keys[i]] + len(line)
                fd.close()
            except (IOError, ValueError) as e:
                logger.error("I/O error on File (%s): Error (%s)" %(log_path[keys[i]], e.strerror))
    time.sleep(5)
