#!/usr/bin/env python
###########################################################################
# Copyright (c) 2018- Franco (nextime) Lanza <franco@unixmedia.it>
#
# Penguidom System Controller Daemon "penguidomd" 
#
# This file is part of penguidomd.
#
# penguidomd 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 3 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, see <http://www.gnu.org/licenses/>.
#
##############################################################################

from twisted.internet import epollreactor
epollreactor.install()


from twisted.internet import reactor, ssl, protocol, endpoints
from twisted.application import service, internet, app, reactors
from twisted.web import server 
import logging, time, sys, os
from nexlibs.daemonizer import Daemonizer
from penguidom import penguidom
from nexlibs.utils.genutils import configFile
from logging import handlers as loghandlers

try:
   import setproctitle
   setproctitle.setproctitle('penguidomd')
   print 'Setting process title to', sys.argv[0]
except:
   pass

loglevels = {
   'info': logging.INFO,
   'warning': logging.WARNING,
   'error': logging.ERROR,
   'critical': logging.CRITICAL,
   'debug': logging.DEBUG
}

#LOGLEN=104857600 # 100 mega
#LOGLEN=10485760 # 10 mega
LOGLEN=26214400 # 25 mega


class penguidomDaemon(Daemonizer):

  def __init__(self):
    self.curdir = os.path.abspath(os.path.dirname(sys.argv[0]))
    log.debug("Reading daemon Config file")
    self.daemoncfg = configFile(self.curdir+'/conf/penguidomd.conf')
    self.daemoncfg.readConfig()
    log.debug("Daemonizing process")
    Daemonizer.__init__(self, self.curdir+'/run/penguidom.pid')

  def main_loop(self):
    log.debug("Main loop called")
    application = service.Application("penguidomd")
    PENGUIDOMServerService = penguidom.penguidomService('penguidomd', curdir=self.curdir, config=self.daemoncfg)
    serviceCollection = service.IServiceCollection(application)
    PENGUIDOMServerService.setServiceParent(serviceCollection)


    IkapServerUDP = PENGUIDOMServerService.getIkapUDP()
    IkapServerTCP = PENGUIDOMServerService.getIkapTCP()

    if str(self.daemoncfg.get('ikap', 'enable')).lower() in ['yes', '1', 'y','true']:
      reactor.listenUDP(int(self.daemoncfg.get('ikap', 'port')), IkapServerUDP, 
            interface=str(self.daemoncfg.get('ikap', 'interface')))
      if self.daemoncfg.get('ikap', 'port') != self.daemoncfg.get('ikap', 'notifyport'):
         reactor.listenUDP(int(self.daemoncfg.get('ikap', 'notifyport')), IkapServerUDP,
            interface=str(self.daemoncfg.get('ikap', 'interface')))
    if str(self.daemoncfg.get('ikap', 'tcpenable')).lower() in ['yes', '1', 'y','true']:
      reactor.listenTCP(int(self.daemoncfg.get('ikap', 'tcpport')), IkapServerTCP,
            interface=str(self.daemoncfg.get('ikap', 'tcpinterface')))


    log.debug("Running reactor")
    reactor.callWhenRunning(PENGUIDOMServerService.isStarted)
    reactor.run()

if __name__ == "__main__":
   # Starting all loggers
   # file di log da 100 mega, per 5 rotazioni 
   formatter = logging.Formatter('%(asctime)s => %(name)-12s: %(levelname)-8s %(message)s')

   logdict={"corelog":
            {"file":"penguidom.log","name":[("Core","general")]},
           "protocollog":
            {"file":"ikap.log","name":
               [("IKAProtocol","ikap"),("IKAPServer","ikap"),("DMDomain","ikap")]},
           } 

   for l in logdict.keys():
      logdict[l]["handler"] = loghandlers.RotatingFileHandler(
         os.path.abspath(os.path.dirname(sys.argv[0]))+'/logs/'+logdict[l]["file"], 'a', LOGLEN, 5)
      logdict[l]["handler"].setLevel(logging.DEBUG)
      logdict[l]["handler"].setFormatter(formatter)

   logging.basicConfig()

   log = logging.getLogger( 'DaemonStarter' )
   log.addHandler(logdict["corelog"]["handler"])
   log.setLevel( logging.INFO )

   curdir = os.path.abspath(os.path.dirname(sys.argv[0]))

   daemoncfg = configFile(curdir+'/conf/penguidomd.conf')
   daemoncfg.readConfig()
   
   for l in logdict.keys():
      for n in logdict[l]["name"]:
         lh = logging.getLogger(n[0])
         lh.setLevel( loglevels[daemoncfg.get(n[1], 'loglevel')] )
         lh.addHandler( logdict[l]["handler"] )

   logging.basicConfig()

   # staring the application
   if len(sys.argv) > 1:
      log.debug("Starting daemon with option "+sys.argv[1]) 
      penguidomDaemon().process_command_line(sys.argv)
   else:
      print 'Please specify start, stop or debug option'