#!/usr/bin/env python3
# Copyright (c) 2018 Arista Networks, Inc.  All rights reserved.
# Arista Networks, Inc. Confidential and Proprietary.

# pylint: disable-msg=pointless-string-statement
# pylint: disable-msg=broad-except
'''
description: Fast Packet transmit service script run
during ASU reboot/ASU hitless reboot
'''

# Pylint gets confused as the script and the library (with a .py exception)
# are named the same.
# pylint: disable-msg=import-self
from AsuFastPktTransmit import AsuFastPktTransmit, log
import sys
import os
import errno
import traceback

def main():
   SECONDS_PER_MINUTE = 60
   cfgDir = os.getenv( "AFPT_CFG_DIR", "/mnt/flash/fastpkttx" )
   backupDir = os.getenv( "AFPT_BACKUP_DIR", "/mnt/flash/fastpkttx.backup" )
   disableFile = os.getenv( "AFPT_DISABLE", "/mnt/flash/disable.fastpkttx" )
   logPath = os.getenv( "AFPT_LOG_PATH", "/mnt/flash/AsuFastPktTransmit.log" )
   maxRunTimeInS = 10 * SECONDS_PER_MINUTE

   simUncaughtExc = os.getenv( "AFPT_SIM_UNCAUGHT_EXC", "False" )

   sys.stdout = open( logPath, "a" ) # pylint: disable=consider-using-with

   log( "Running AsuFastPktTransmit service" )

   if os.path.exists( disableFile ):
      # pylint: disable-next=consider-using-f-string
      log( "Skipping AsuFastPktTransmit as %s exists" % ( disableFile ) )
      return

   # Make sure the backup directory exists. ConfigParser will catch if the configDir
   # is not present and thorw an error that propagates up.
   try:
      os.makedirs( backupDir )
   except OSError as e:
      if e.errno == errno.EEXIST and os.path.isdir( backupDir ):
         pass
      else:
         # pylint: disable-next=consider-using-f-string
         log( "ERROR: %s doesn't exist and couldn't create" % ( backupDir ) )
         exit( 1 ) # pylint: disable=consider-using-sys-exit
         raise

   try:
      AsuFastPktTransmit( cfgDir, backupDir, maxRunTimeInS ).run(
            simulateUncaughtExc=simUncaughtExc )
   except Exception as e: # pylint: disable=unused-variable
      # Top level - catch any uncaught exceptions here as a last gasp and print out
      # traceback. Will make it easier in future to catch issues like bug 355888
      # that were previously printing nothing in the log when AFPT failed with
      # an uncaught exception.
      #
      # N.B. YES, I want to catch all exceptions here. This way I catch everything
      # and have a chance to print out the backtrace in the logfile so we have
      # something to go on, rather than a blank early exit
      log( traceback.format_exc() )
      raise

if __name__ == '__main__':
   main()
