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

import argparse
import errno
import re
import sys

from SectionCliLib import sectionFilter, sectionFilterAll

def main():
   parser = argparse.ArgumentParser( description="Show sections containing <regex>" )
   parser.add_argument( "--all", action="store_true",
                        help="Display matching sections "
                             "including same-level commands." )
   parser.add_argument( "regexList", type=str, nargs="+",
                        help="regular expression to find." )
   parser.add_argument( "-version", action="version", version="%(prog)s 2.0" )

   # There are multiple ways to invoke section and each delivers args in
   # different ways. When invoked from a shell, argv is as expected:
   #     bash: cat ribd-tech.txt > section --all regex
   #     sys.argv = ['/usr/bin/section', '--all', 'regex']
   # However, when invoked from the cli, all command line arguments may be
   # delivered in a single string:
   #     rtr1# show run | section all regex1 regex2
   #     sys.argv= ['/usr/bin/section', '--all', 'regex1 regex2']
   #     rtr1# show run | section  regex
   #     sys.argv= ['/usr/bin/section', 'regex']
   # Note that the non-piped cli section commands (e.g. show run section regex)
   # directly call sectionFilter.
   if len( sys.argv ) <= 1:
      parser.error( "% Invalid Input" )
   else:
      argv = []
      for arg in sys.argv[1:]:
         argv += arg.split( ' ' )
   args = parser.parse_args( argv )
   if not args.regexList:
      parser.error( "% Invalid Input" )
   sectionFilterFn = sectionFilterAll if args.all else sectionFilter
   try:
      sectionFilterFn( sys.stdin.readlines(), args.regexList )
   except KeyboardInterrupt:
      pass
   except OSError 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__":
   try:
      main()
   except KeyboardInterrupt:
      pass
