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

import sys, optparse, re # pylint: disable=deprecated-module
import LoggingLib

headerRe = re.compile( "^(?:Syslog logging:|Log Buffer:)" )
repeatedMsgRe = re.compile( "message repeated .+ times" )

if __name__ == '__main__':
   usage = """sev-filter [options] <severity-level>

   Filters input log messages by severity level:
   """ + ' '.join( sorted( LoggingLib.logSevCliToValueMap.keys(), 
                           key=LoggingLib.severityCliToValue ) )

   parser = optparse.OptionParser( usage=usage )
   parser.add_option( '-t', '--threshold', action='store_true', default=False, 
                      help="display log messages at given severity and above" )
   options, args = parser.parse_args( args=sys.argv )
   if len( args ) != 2:
      parser.print_usage()
      sys.exit( 1 )
   severityName = args[ 1 ]

   try:
      severityValue = LoggingLib.severityCliToValue( severityName )
   except KeyError:
      parser.error( severityName + ' not a valid severity level' )
      sys.exit( 1 )
   sevFilter = '^[^%]*%[^-]+'
   if options.threshold:
      # pylint: disable-next=consider-using-f-string
      sevFilter += '-[0-%d]-' % severityValue
   else:
      sevFilter += '-%d-' % severityValue # pylint: disable=consider-using-f-string
   sevFilterRe = re.compile( sevFilter )
   matchSeen = False
   for line in sys.stdin:
      if matchSeen and repeatedMsgRe.search( line ):
         print( line, end=' ' )
         continue
      matchSeen = False
      if ( headerRe.match( line ) or sevFilterRe.match( line ) ):
         matchSeen = True
         print( line, end=' ' )
         continue
