#!/usr/bin/env python
###########################################################################
# Copyright (c) 2018- Franco (nextime) Lanza <franco@nexlab.it>
#
# Penguidom System client Daemon "penguidomd"  [https://git.nexlab.net/domotika/Penguidom]
#
# This file is part of penguidom.
#
# penguidom 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

from OpenSSL import SSL

class PenguiSSLContext(ssl.DefaultOpenSSLContextFactory):

   def cacheContext(self):
      if self._context is None:
         ctx = self._contextFactory(self.sslmethod)
         # Disallow SSLv2!  It's insecure!  SSLv3 has been around since
         # 1996.  It's time to move on.
         ctx.set_options(SSL.OP_NO_SSLv2)
         ctx.use_certificate_chain_file(self.certificateFileName)
         ctx.use_privatekey_file(self.privateKeyFileName)
         self._context = ctx



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()
    WebAuthServer = PENGUIDOMServerService.getAuthWebServer()
    privkey = self.daemoncfg.get('web', 'privkey')
    cacert = self.daemoncfg.get('web', 'cacert')
    if not privkey.startswith('/'): privkey="/".join([self.curdir, privkey])
    if not cacert.startswith('/'): cacert="/".join([self.curdir, cacert])
    sslContext = PenguiSSLContext(privkey, cacert)
    if str(self.daemoncfg.get('web', 'enable')).lower() in ['yes', '1', 'y','true']:
      reactor.listenSSL(int(self.daemoncfg.get('web', 'sslport')), WebAuthServer,
             contextFactory=sslContext,
             interface=str(self.daemoncfg.get('web', 'interface')))

      if not str(self.daemoncfg.get('web', 'sslonly')).lower() in ['yes', '1', 'y','true']:
         reactor.listenTCP(int(self.daemoncfg.get('web', 'port')), WebAuthServer,
                 interface=str(self.daemoncfg.get('web', 'interface')))


    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 
   LOGFORMAT='%(asctime)s => %(name)-12s: %(levelname)-8s %(message)s'
   formatter = logging.Formatter(LOGFORMAT)

   logdict={"corelog":
            {"file":"penguidom.log","name":[("Core","general")]},
            "weblog":
            {"file":"web.log","name":[("Webgui","web")]},
            "pluginslog":
            {"file":"plugins.log","name":[("Plugins","plugins")]},
           "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(format=LOGFORMAT)

   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(format=LOGFORMAT)

   # 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'