#!/usr/bin/python3.6 -s

# Copyright (c) 2019 Paolo Patruno <p.patruno@iperbole.bologna.it>
# This program is free software; you can redistribute it and/or modify 
# it under the terms of 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. 
# 
# This program is distributed in the hope that it will be useful, 
# but WITHOUT ANY WARRANTY; without even the implied warranty of 
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
# GNU General Public License for more details. 
# 
# You should have received a copy of the GNU General Public License 
# along with this program; if not, write to the Free Software 
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA 

__author__ = "Paolo Patruno"
__copyright__ = "Copyright (C) 2019 by Paolo Patruno"


import signal
import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'rmap.settings'
import django
django.setup()

from rmap import daemon
from rmap import __version__
import rmap.settings
from rmap.report2observation import report2observation

logfile=rmap.settings.logfilereport2observationd
errfile=rmap.settings.errfilereport2observationd
lockfile=rmap.settings.lockfilereport2observationd
user=rmap.settings.userreport2observationd
group=rmap.settings.groupreport2observationd


mqtt_report2observationd = daemon.Daemon(
        stdin="/dev/null",
        stdout=logfile,
        stderr=errfile,
        pidfile=lockfile,
        user=user,
        group=group
)


# catch signal to terminate the process
class GracefulKiller:
    kill_now = False
    def __init__(self):
        signal.signal(signal.SIGINT, self.exit_gracefully)
        signal.signal(signal.SIGTERM, self.exit_gracefully)

    def exit_gracefully(self,signum, frame):
        self.kill_now = True



def main (self):

    import os,sys,time
    import logging,logging.handlers
    import subprocess
    import traceback

    #arm the signal handler
    killer = GracefulKiller()
    
    # configure the logger
#    formatter=logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(thread)d - %(message)s",datefmt="%Y-%m-%d %H:%M:%S")
    formatter=logging.Formatter("%(asctime)s%(thread)d-%(levelname)s- %(message)s",datefmt="%Y-%m-%d %H:%M:%S")
    handler = logging.handlers.RotatingFileHandler(self.options.stdout, maxBytes=5000000, backupCount=10)
    handler.setFormatter(formatter)
    
    # Add the log message handler to the root logger
    logging.getLogger().addHandler(handler)
    logging.getLogger().setLevel(logging.INFO)

    logging.info('Starting up mqtt_report2observationd')

    try:

        subtopics=[
            "report/+/+/+","report/+/+/+/+/+"
            ,"1/report/+/+/+/+","1/sample/+/+/+/+"
            ,"1/report/+/+/+/+/+/+","1/sample/+/+/+/+/+/+"
            ,"report/+/+/+/","report/+/+/+/+/+/"
            ,"1/report/+/+/+/+/","1/sample/+/+/+/+/"
            ,"1/report/+/+/+/+/+/+/","1/sample/+/+/+/+/+/+/"
        ]
        
        r2o=report2observation(rmap.settings.mqtthost,rmap.settings.mqttuser, rmap.settings.mqttpassword
                               , subtopics, rmap.settings.topicmaint, killer)
        r2o.run()
        
        #while True:
        #    if killer.kill_now:
        #        logging.info("killed by signal\n")
        #        #terminate.set()
        #        break


    except Exception as exception:
        # log and retry on exception 
        logging.error('Exception occured: ' + str(exception))
        logging.error(traceback.format_exc())
        logging.error('daemon failed')
        #time.sleep(10)


    except KeyboardInterrupt:
        # terminate on keyboard interrupt
        sys.stdout.write("keyboard interrupt\n")
        logging.info("keyboard interrupt\n")
        #terminate.set()
    finally:
        # check if we have to terminate together with other exceptions
        #terminate.set()
        pass
    
    #logging.info("wait for thread to terminate")
    #for th in threads:
    #    th.join()

            
if __name__ == '__main__':
    
    import sys, os
    
    mqtt_report2observationd.cwd=os.getcwd()

    if mqtt_report2observationd.service():

        sys.stdout.write("Daemon started with pid %d\n" % os.getpid())

        main(mqtt_report2observationd)  # (this code was run as script)
            
        for proc in mqtt_report2observationd.procs:
            proc.wait()

        sys.stdout.write("Daemon stoppped\n")
        sys.exit(0)
