#!/usr/bin/env python3

# Copyright (c) 2021 Arista Networks, Inc.  All rights reserved.
# Arista Networks, Inc. Confidential and Proprietary.

import sys
import socket
import traceback
import time
import argparse

ERROR_NONE = 0
ERROR_UNKNOWN = 1
ERROR_CONNECT = 2

# pylint: disable=broad-except

#
# Issue a command to the bsn network cli.
#
ap = argparse.ArgumentParser("BSN Network CLI.")
ap.add_argument("--wait",
      type=int,
      help="Wait the given number of seconds for bsn to become available.",
      default=1)
ap.add_argument("--server", help='Target bsn server.', default='localhost')
ap.add_argument("--port", help="Target bsn port.", type=int, default=4454)
ap.add_argument("command", nargs='*', help="The bsn command.")

ops = ap.parse_args()

def connect(server, port, attempts):

   attempts = max( attempts, 1 )

   while attempts > 0:
      s_ = socket.socket()
      try:
         s_.connect((server, port))
         return s_
      except Exception:
         s_.close()
         attempts -= 1
         time.sleep(1)

   return None


s = connect(ops.server, ops.port, ops.wait)
if s is None:
   sys.stderr.write("Service temporarily unavailable.\n")
   sys.exit(ERROR_CONNECT)

cmd = " ".join(ops.command) + "\n"

try:
   s.send(cmd.encode())

   while True:
      data = s.recv(1024)
      if data:
         sys.stdout.write(data.decode())
      else:
         break

except Exception:
   s.close()
   traceback.print_exc(None, None)
   sys.exit(ERROR_UNKNOWN)

s.close()
sys.exit(ERROR_NONE)
