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

import subprocess, re, os, sys

internalAddrPattern = r'(127\.\d+\.\d+\.\d+)'

sshd = os.environ.get( 'ISSHD_PROG', '/usr/sbin/sshd' )
port = os.environ.get( 'ISSHD_PORT', '3601' )
config = os.environ.get( 'ISSHD_CONFIG', '/usr/share/Arsys/issh/sshd_config' )

# pylint: disable-next=consider-using-with
out = subprocess.Popen( ['ip','-f','inet','-o','addr','show'],
                        stdout=subprocess.PIPE, universal_newlines=True
                      ).communicate()[ 0 ]
patstr = r'\d+:\s*\S+\s+inet\s+' + internalAddrPattern
path = re.compile( patstr )
internalAddrs = []
for line in out.split('\n'):
   m = re.match( patstr, line )
   if m:
      addr = m.group(1)
      if addr != '127.0.0.1':
         internalAddrs.append( m.group(1) )

if internalAddrs:
   sshOptions = []
   for i in internalAddrs:
      sshOptions += [ "-o",f"ListenAddress={i}:{port}" ]
   sshArgv = []
   dashN = False
   for i in sys.argv[1:]:
      if i == '-n':
         dashN = True
      else:
         sshArgv.append( i )
   args = [sshd, '-f',config,'-p',port] + sshOptions + sshArgv
   if dashN:
      print( sshd + " " + " ".join( args ) )
   else:
      os.execv( sshd, args )
else:
   # No internal interfaces found. We're probably on a fixed system
   # with no internal interfaces. Exit quietly - don't want to generate
   # alarming error messages during boot.
   pass
