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

# Performs an authorization check for executing a shell, and if allowed,
# execs /usr/bin/Cli.

# This disables importing Tac
import CliShellTracing
CliShellTracing.install()

# Set the 'NOPDB' environment variable to prevent us from ever dropping into
# PDB, as doing so could permit a security violation.
import os # pylint: disable=wrong-import-position
os.environ[ 'NOPDB' ] = '1'

# pylint: disable-next=wrong-import-position,import-self,deprecated-module
import RunCli, optparse, sys

usage = """
RunCli [--sysname <sysname>]

RunCli performs an "exec" authorization check to the Aaa agent, and if
it succeeds, execs /usr/bin/Cli. 

Use --help option to see full usage message, including options."""

parser = optparse.OptionParser( usage=usage )
parser.add_option( "-s", "--sysname", action="store", default="ar",
                   help="system name (default: %default)" )
parser.add_option( "-c", "--command", action="store",
                   help="run COMMAND non-interactively; separate multiple "
                   "commands with carriage returns" )
parser.add_option( "--uid", action="store", type=int, default=None,
                   help=optparse.SUPPRESS_HELP )
( options, args ) = parser.parse_args()
if args:
   print( "Unknown args: " + " ".join( args ) )

sysname = os.environ.get( "SYSNAME", options.sysname )
try:
   # This never returns if everything goes well
   # pylint: disable-next=c-extension-no-member
   RunCli.authorizeAndExecCli( sysname, command=options.command,
                               uid=options.uid )
except RunCli.AuthzDeniedError as e: # pylint: disable=c-extension-no-member
   # pylint: disable-next=consider-using-f-string
   print( "Authorization denied: %s" % e, file=sys.stderr )
except KeyboardInterrupt:
   # This can happen if someone hits Ctrl-C.
   pass
except:
   print( "An error occurred during authorization", file=sys.stderr )
   raise
sys.exit( 1 )
