# @package      hubzero-submit-monitors
# @file         ManageIdentities.py
# @copyright    Copyright (c) 2004-2020 The Regents of the University of California.
# @license      http://opensource.org/licenses/MIT MIT
#
# Copyright (c) 2004-2020 The Regents of the University of California.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
# HUBzero is a registered trademark of The Regents of the University of California.
#
import sys
import os
import select
import signal
import time
import logging
from errno import EINTR

from hubzero.submit.LogMessage        import getLogPIDMessage as getLogMessage
from hubzero.submit.DaemonsInfo       import DaemonsInfo
from hubzero.submit.IdentitiesManager import IdentitiesManager

class ManageIdentities:
   def __init__(self,
                daemonsDirectory,
                daemonsConfigurationFile,
                infosDirectory,
                infosConfigurationFile,
                identityDirectory,
                proxyBinDirectory,
                activityUpdateInterval):
      self.logger = logging.getLogger(__name__)
 
      self.activityUpdateInterval = activityUpdateInterval

      configFilePath = os.path.join(daemonsDirectory,daemonsConfigurationFile)
      daemonsInfo    = DaemonsInfo(configFilePath)
      self.listenURI = daemonsInfo.getDaemonListenURI('identitiesManager','tcp')
      self.identitiesManager = IdentitiesManager(daemonsDirectory,
                                                 daemonsConfigurationFile,
                                                 infosDirectory,
                                                 infosConfigurationFile,
                                                 identityDirectory,
                                                 proxyBinDirectory,
                                                 self.listenURI)
      self.setInfoError = self.identitiesManager.setInfo()

      self.terminateIdentitiesManager = False
      self.resetInfo                  = False

      self.exitSystemCallOnInterrupt = False

      signal.signal(signal.SIGINT,self.sigINT_handler)
      signal.signal(signal.SIGHUP,self.sigHUP_handler)
      signal.signal(signal.SIGQUIT,self.sigQUIT_handler)
      signal.signal(signal.SIGABRT,self.sigABRT_handler)
      signal.signal(signal.SIGTERM,self.sigTERM_handler)


   def terminate(self):
      self.terminateIdentitiesManager = True


   def sigGEN_handler(self,
                      signalNumber,
                      frame):
      self.terminate()
      if self.exitSystemCallOnInterrupt:
         if sys.version_info > (3,):
            raise InterruptedError(EINTR,"System Call Interrupt")


   def sigINT_handler(self,
                      signalNumber,
                      frame):
      self.logger.log(logging.INFO,getLogMessage("Received SIGINT!"))
      self.resetInfo = True


   def sigHUP_handler(self,
                      signalNumber,
                      frame):
      self.logger.log(logging.INFO,getLogMessage("Received SIGHUP!"))
      self.sigGEN_handler(signalNumber,frame)


   def sigQUIT_handler(self,
                       signalNumber,
                       frame):
      self.logger.log(logging.INFO,getLogMessage("Received SIGQUIT!"))
      self.sigGEN_handler(signalNumber,frame)


   def sigABRT_handler(self,
                       signalNumber,
                       frame):
      self.logger.log(logging.INFO,getLogMessage("Received SIGABRT!"))
      self.sigGEN_handler(signalNumber,frame)


   def sigTERM_handler(self,
                       signalNumber,
                       frame):
      self.logger.log(logging.INFO,getLogMessage("Received SIGTERM!"))
      self.sigGEN_handler(signalNumber,frame)


   def manage(self):
      if not self.identitiesManager.isListening():
         self.logger.log(logging.ERROR,getLogMessage("Port binding failed"))
         sys.exit(1)

      self.logger.log(logging.INFO,getLogMessage("******************************"))
      self.logger.log(logging.INFO,getLogMessage("* identities manager started *"))
      self.logger.log(logging.INFO,getLogMessage("******************************"))

      if self.setInfoError:
         self.identitiesManager.terminate()
      else:
         if self.identitiesManager.checkScriptPaths():
            self.identitiesManager.terminate()
         else:
            self.identitiesManager.generateCommunityGridProxies()
            self.identitiesManager.generateCommunityVomsProxies()
            self.identitiesManager.generatePermanentUserProxies()
            self.identitiesManager.scheduleRefreshProxies()
            self.identitiesManager.generatePermanentUserSSHKey()
            self.identitiesManager.generatePermanentUserSSHKeyPair()
            self.identitiesManager.scheduleRefreshOauthTokens()

      while True:
         listeningSocket,activeReaders = self.identitiesManager.getInputObjects()
         activeWriters                 = self.identitiesManager.getOutputObjects()
         if not listeningSocket and not activeReaders and not activeWriters:
            self.logger.log(logging.INFO,getLogMessage("******************************"))
            self.logger.log(logging.INFO,getLogMessage("* identities manager stopped *"))
            self.logger.log(logging.INFO,getLogMessage("******************************"))
            break
#        if not listeningSocket:
#           self.logger.log(logging.DEBUG,getLogMessage("listeningSocket: " + str(listeningSocket)))
#        if not activeReaders:
#           self.logger.log(logging.DEBUG,getLogMessage("activeReaders: " + str(activeReaders)))
#        if not activeWriters:
#           self.logger.log(logging.DEBUG,getLogMessage("activeWriters: " + str(activeWriters)))

         try:
            self.exitSystemCallOnInterrupt = True
            if self.identitiesManager.isEmpty():
               readyReaders,readyWriters,readyExceptions = select.select(listeningSocket+activeReaders,
                                                                         activeWriters,
                                                                         [],
                                                                         self.activityUpdateInterval)
            else:
               maximumWaitTime = self.identitiesManager.getNextEventTime() - time.time()
               if maximumWaitTime > 0.:
                  readyReaders,readyWriters,readyExceptions = select.select(listeningSocket+activeReaders,
                                                                            activeWriters,
                                                                            [],
                                                                            maximumWaitTime)
               else:
                  readyReaders = []
                  readyWriters = []
         except select.error as e:
            if e.args[0] == EINTR:
               readyReaders = []
               readyWriters = []
            else:
               self.terminate()
         finally:
            self.exitSystemCallOnInterrupt = False

#        self.logger.log(logging.DEBUG,getLogMessage("ready to process: " + str(self.terminateIdentitiesManager)))

         self.identitiesManager.processEvents()

         for readyReader in readyReaders:
            if   readyReader in listeningSocket:
               if not self.identitiesManager.acceptConnection():
                  self.logger.log(logging.ERROR,getLogMessage("Connection failed."))
            elif readyReader in activeReaders:
               self.identitiesManager.receiveMessage(readyReader)

         self.identitiesManager.processRequests()

         for readyWriter in readyWriters:
            if readyWriter in activeWriters:
               self.identitiesManager.sendMessage(readyWriter)

         if self.terminateIdentitiesManager:
            self.identitiesManager.terminate()

         if self.resetInfo:
            self.setInfoError = self.identitiesManager.setInfo()
            if self.setInfoError:
               self.resetInfo = False
               self.identitiesManager.terminate()
            else:
               self.identitiesManager.purge()
               self.identitiesManager.generateCommunityGridProxies()
               self.identitiesManager.generateCommunityVomsProxies()
               self.identitiesManager.generatePermanentUserProxies()
               self.identitiesManager.scheduleRefreshProxies()
               self.identitiesManager.generatePermanentUserSSHKey()
               self.identitiesManager.generatePermanentUserSSHKeyPair()
               self.identitiesManager.scheduleRefreshOauthTokens()
               self.resetInfo = False


