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

import sys, optparse, re, errno
from SectionCliLib import sectionFilter #pylint: disable-msg=E0611,F0401

def main():
   parser = optparse.OptionParser( usage = "usage: %prog [options] <regex>",
                                   version = "%prog 1.0" )
   parser.disable_interspersed_args()
   opts, regexList = parser.parse_args() # pylint: disable-msg=W0612
   if len( regexList ) == 0:
      parser.error( "% Invalid Input" )
   if len( regexList ) == 1:
      #Hack to work around Cli giving us only 1 arg
      regexList = regexList[0].split(' ')
   try:
      sectionFilter( sys.stdin.readlines(), regexList )
   except KeyboardInterrupt:
      pass
   except EnvironmentError as e:
      if e.errno == errno.EPIPE:
         pass
      else:
         print e.errno, e.strerror
         sys.exit( 2 )
   except re.error:
      print "% Invalid regular expression provided"
      sys.exit( 2 )


if __name__ == "__main__":
   # I cannot explain it, but only through this second layer, 
   # can I catch it. Without either it'll show the KeyboardInterrupt and 
   # back trace
   try:
      main()
   except KeyboardInterrupt:
      pass


