#==============================================================
#
#  Abs:   Script for getting the IOC at a terminal server port
#
#  Name:  getIOCAtPort.py
#
#  Rem:   This script reads screeniocs to determine the IOC
#         that is on a terminal server at a specified port.
#
#  Facility: SLAC Controls
#
#  Auth:  09-Aug-2019, A. Le (anle)
#--------------------------------------------------------------
#  Mods: (Latest to oldest)
#
#==============================================================
#
import subprocess

def getIOCAtPort(screeniocsFileName, terminalServer, portNumber):
    '''Gets the IOC that is on a terminal server at a specified port'''
    awkScript = '/^[^#]/{{if($3 ~ /^[0-9]+$/ && $2 == "{}" && $3 == "{}"){{print $1;}}}}'.format(terminalServer, portNumber)
    commandAndArgs = ['awk', awkScript, screeniocsFileName]
    proc = subprocess.Popen(commandAndArgs, stdout=subprocess.PIPE)
    stdout = proc.communicate()[0]
    return stdout.split('\n')[0]
