#!/usr/bin/env python

'''This module parses the screen IOCs file. The main method is the parseScreenIOCs.'''
from __future__ import print_function

import re
import sys

import globals

# Patterns
name = re.compile(r'[A-Za-z\d]+')
number = re.compile(r'\d+')
path = re.compile(r'/[A-Za-z\d\-_/]+')


def parseScreenIOCs(screenIOCsFileName):
    '''Parse the screen IOCs file, which can be in either the old or new format.'''
    # Get format number
    format = getScreenIOCsFormat(screenIOCsFileName)

    # 0 means old format, >=1 means new
    if format >= 1:
        return parseNewScreenIOCs(screenIOCsFileName)

    return parseOldScreenIOCs(screenIOCsFileName)


def getScreenIOCsFormat(screenIOCsFileName):
    '''Determine the format of screeniocs by reading the first line.

    # FORMAT=1, 2, ... ==> new version
    # FORMAT=0         ==> old version
    (neither)          ==> old version
    '''
    # Check for version string at the top
    with open(screenIOCsFileName) as f:
        firstLine = f.readline()

    # Extract version number
    pattern = re.compile(re.escape(globals.formatIndicator) + r'(\d+)')
    match = pattern.match(firstLine)
    if match:
        return int(match.group(1))

    # If version number not found or invalid, return 0 (old version)
    if globals.verbose:
        print("screeniocs version number not found or invalid, assuming old version")

    return 0


def parseOldScreenIOCs(screenIOCsFileName):
    '''Parse the screen IOCS file whose path is specified in screenIOCsFileName and return a dict of IOCName -> Info.
    Info can be one of these types - the type of the info is in the type column
    1) type:IOC - All hard IOCs connecting thru a terminal server have names that begin with ioc/eioc. For example, ioc-b34-bp02.
    These have columns for
    1.1) iocName/Alias
    1.2) Terminal
    1.3) Port No.
    1.4) Host where screen is run
    1.5) Comments (need not start with #)
    For example,
    ioc-b34-bp02 ts-b34-nw01     2002       lcls-dev1       # bpm test ioc
    2)type:SIOC - All soft IOCs for whom we expect an executable path have names that begin with sioc. For example, sioc-sys0-cv01.
    These have columns for
    2.1) iocName/Alias
    2.2) Full path to executable
    2.3) A fixed field that is always the string sioc
    2.4) Host where screen is run
    2.5) Comments (need not start with #)
    For example,
    sioc-sys0-cv01 /afs/slac/g/lcls/epics/iocCommon/sioc-sys0-cv01/bin/CAMACSoft            sioc     lcls-dev1
    3) type:VIOC - All hard IOCs connecting thru a SSH session have names that begin with a vioc. For example, vioc-b15-mg01
    These have columns for
    3.1) iocName/Alias
    3.2) Machine name hosting the IOC+ssh session
    3.3) UserID that we ssh as.
    3.4) Comments (need not start with #)
    For example,
    vioc-b15-mg01         eioc-b15-mg01         laci       lcls-dev1     embedded ATOM-MCOR IOC Test Stand.
    '''
    if globals.verbose:
        print("Parsing screenIOCs file {0} (OLD format)".format(screenIOCsFileName))

    iocInfos = {}
    with open(screenIOCsFileName) as f:
        for line in f.read().splitlines():
            currentIOCInfo = {}
            trimmed_line = line.strip()
            # Ignore empty lines and comments
            if not trimmed_line or trimmed_line.startswith('#'):
                continue

            # Split lines into 4-5 columns
            columns = line.split(None, 4)
            if len(columns) < 3:
                raise ValueError("Error parsing screenioc line: {}".format(line))

            # Reject invalid IOC name
            if not name.match(columns[0]):
                raise ValueError("Invalid IOC name: {}".format(columns[0]))

            currentIOCInfo['name'] = columns[0]

            # For SIOCs, column 3 is "sioc"
            if columns[2] == 'sioc':
                currentIOCInfo['type'] = 'SIOC'
                currentIOCInfo['executable'] = columns[1]
                currentIOCInfo['screenhost'] = columns[3]
                if len(columns) > 4:
                    currentIOCInfo['description'] = columns[4]

            elif number.match(columns[2]):
                # For HIOCs, column 3 is a port number
                currentIOCInfo['type'] = 'HIOC'
                currentIOCInfo['terminalserver'] = columns[1]
                currentIOCInfo['port'] = columns[2]
                currentIOCInfo['screenhost'] = columns[3]
                if len(columns) > 4:
                    currentIOCInfo['description'] = columns[4]

            elif name.match(columns[2]):
                # For VIOCs, column 3 is a generic name
                currentIOCInfo['type'] = 'VIOC'
                currentIOCInfo['terminalserver'] = columns[1]
                currentIOCInfo['user'] = columns[2]

                # Optionally, a path to the executable can be in column 4
                if len(columns) > 3:
                    if path.match(columns[3]):
                        currentIOCInfo['executable'] = columns[3]
                        if len(columns) > 4:
                            currentIOCInfo['description'] = columns[4]

                    else:
                        currentIOCInfo['description'] = ' '.join(columns[3:])

            else:
                # Invalid line
                raise ValueError("Error parsing screenioc line: {}".format(line))

            # Add IOC info to dict
            iocInfos[currentIOCInfo['name']] = currentIOCInfo

    return iocInfos


def parseNewScreenIOCs(newScreenIOCsFileName):
    '''Parses the newly formatted IOC file and outputs the data in the dictionary 'newIOCinfos. The data is in column format and follows the pattern:
    Column 1: IOC type (SIOC, HIOC, or VIOC)
    Column 2: IOC Name/Alias
    Column 3: User ID that we ssh as and the host where the screen is run
    Column 4:
        For HIOCs, User ID that we ssh as, terminal, and port number
        For SIOCs and VIOCs, full executable path (optional)
    Column 5: Comments (starts with '#', optional)
    For example,
        SIOC     sioc-alh0-misc00   laci@lcls-dev1       /afs/slac/g/lcls/epics/iocCommon/sioc-alh0-misc00/iocSpecificRelease/bin/rhel6-x86_64/alhPV
        HIOC     cpu-b033-sp01      laci@lcls-dev1       laci@ts-b033-nw02:2001 # CPU
        VIOC     sioc-b084-rg01     laci@cpu-b084-sp02.
    '''
    if globals.verbose:
        print("Parsing screenIOCs file {0} (NEW format)".format(newScreenIOCsFileName))

    newIOCinfos = {}
    with open(newScreenIOCsFileName) as f:
        for line in f.read().splitlines():
            currentIOCInfo = {}
            trimmed_line = line.strip()

            # Ignore empty lines and comments
            if not trimmed_line or trimmed_line.startswith('#'):
                continue

            # Split lines into 4-5 columns
            columns = line.split(None, 4)
            if len(columns) < 3:
                raise ValueError("Error parsing screenioc line: {}".format(line))

            # Reject invalid IOC name
            if not name.match(columns[1]):
                raise ValueError("Invalid IOC name: {}".format(columns[1]))

            if columns[0] in ('SIOC', 'NIOC'):
                # If line is SIOC or NIOC (same fields as SIOC)
                currentIOCInfo['type'] = columns[0]
                currentIOCInfo['name'] = columns[1]
                screenhostInfo = columns[2]
                if len(columns) > 3:
                    if path.match(columns[3]):
                        currentIOCInfo['executable'] = columns[3]
                        if len(columns) > 4:
                            currentIOCInfo['description'] = columns[4]
                    else:
                        currentIOCInfo['description'] = ' '.join(columns[3:])

                # Split screenhost info into user and node
                try:
                    _, tsNode = screenhostInfo.split('@', 1)
                except ValueError as e:
                    raise ValueError("Expecting user@node for screenhost: {}".format(line)) from e

                currentIOCInfo['screenhost'] = tsNode

            elif columns[0] == 'HIOC':
                # If line is HIOC
                currentIOCInfo['type'] = columns[0]
                currentIOCInfo['name'] = columns[1]
                screenhostInfo = columns[2]
                tsInfo = columns[3]
                if len(columns) > 4:
                    currentIOCInfo['description'] = columns[4]

                # Split screenhost info into user and node
                try:
                    _, tsNode = screenhostInfo.split('@', 1)
                except ValueError as e:
                    raise ValueError("Expecting user@node for screenhost: {}".format(line)) from e

                currentIOCInfo['screenhost'] = tsNode

                # Split TS info into user, node, and port
                try:
                    _, tsNodePort = tsInfo.split('@', 1)
                    tsNode, tsPort = tsNodePort.split(':', 1)
                except ValueError as e:
                    raise ValueError("Expecting user@node:port for terminal server: {}".format(line)) from e

                currentIOCInfo['terminalserver'] = tsNode
                currentIOCInfo['port'] = tsPort

            elif columns[0] == 'VIOC':
                # If line is VIOC
                currentIOCInfo['type'] = columns[0]
                currentIOCInfo['name'] = columns[1]
                cpuInfo = columns[2]
                if len(columns) > 3:
                    if path.match(columns[3]):
                        currentIOCInfo['executable'] = columns[3]
                        if len(columns) > 4:
                            currentIOCInfo['description'] = columns[4]
                    else:
                        currentIOCInfo['description'] = ' '.join(columns[3:])

                # Split CPU info into user and node
                try:
                    user, tsNode = cpuInfo.split('@', 1)
                except ValueError as e:
                    raise ValueError("Expecting user@node for computer host: {}".format(line)) from e

                currentIOCInfo['user'] = user
                currentIOCInfo['terminalserver'] = tsNode

            # Add parsed info to dict
            newIOCinfos[currentIOCInfo['name']] = currentIOCInfo

    return newIOCinfos


def getIOCsByScreenhost(iocs, ioc_regex, screenhost_regex=None, show_screenhost=False):
    '''Given a dictionary of IOC info, return a list of IOCs on a screenhost.
    If screenhost is not provided, return all IOCs.
    If show_screenhost is True, append the screenhost next to each IOC.'''
    if screenhost_regex:
        if show_screenhost:
            # Return IOCs:screenhosts when matching screenhost
            return sorted(set('{}:{}'.format(ioc, info.get('screenhost', '')) for ioc, info in iocs.items() if re.fullmatch(ioc_regex, info.get('name')) and re.fullmatch(screenhost_regex, info.get('screenhost', ''))))

        # Return IOCs on screenhost
        return sorted(set(ioc for ioc, info in iocs.items() if re.fullmatch(ioc_regex, info.get('name')) and re.fullmatch(screenhost_regex, info.get('screenhost', ''))))

    if show_screenhost:
        # Return all IOCs:screenhosts
        return sorted(set('{}:{}'.format(ioc, info.get('screenhost', '')) for ioc, info in iocs.items() if re.fullmatch(ioc_regex, info.get('name'))))

    # Return all IOCs
    return sorted(set(ioc for ioc, info in iocs.items() if re.fullmatch(ioc_regex, info.get('name'))))


def getIOCsByCPU(iocs, cpuName=None):
    '''Given a dictionary of IOC info and a CPU, return a list of LinuxRT IOCs on that CPU.
    If CPU is not provided, return all LinuxRT IOCs.'''
    if cpuName:
        # Return all LinuxRT IOCs on a CPU
        # CPU is stored under terminalserver
        return sorted(set(ioc for ioc, info in iocs.items() if info.get('type') == 'VIOC' and info.get('terminalserver') == cpuName))

    # Return all LinuxRT IOCs
    return sorted(set(ioc for ioc, info in iocs.items() if info.get('type') == 'VIOC'))


def getTSByHIOC(iocs, hiocName=None):
    '''Given a dictionary of IOC info and a hard IOC, return the terminal server and port to which it is connected.
    If HIOC is not provided, return all terminal servers.'''
    if hiocName:
        # Get terminal server and port
        # TODO: handle missing terminal server or port
        if hiocName not in iocs:
            return '', ''

        iocInfo = iocs[hiocName]
        terminalServer = iocInfo.get('terminalserver', '')
        port = iocInfo.get('port', '')
        return terminalServer, port

    # Return all terminal servers
    return sorted(set(info.get('terminalserver') for info in iocs.values() if info.get('type') == 'HIOC' and 'terminalserver' in info and info.get('terminalserver').startswith('ts-')))


def getIOCsByTS(iocs, tsName):
    '''Given a dictionary of IOC info and a terminal server, return the IOCs/CPUs connected to the terminal server.'''
    if tsName:
        # Exclude LinuxRT IOCs
        return sorted(set(ioc for ioc, info in iocs.items() if info.get('type') != 'VIOC' and info.get('terminalserver') == tsName))


def getScreenIOCsEntry(iocName, screenIOCsFileName):
    '''Get the current entry in screeniocs for the given IOC; if present
    For the purposes of this method, screeniocs is treated as a file with name value lines.
    As inputs, we expect two arguments
    iocName - name of the IOC
    screenIOCsFileName - path of screeniocs
    We return the complete line in screeniocs as is.
    '''
    # Get format number
    format = getScreenIOCsFormat(screenIOCsFileName)

    # Read screeniocs
    with open(screenIOCsFileName) as f:
        lines = f.readlines()
    for line in lines:
        line = line.strip()
        if not line:
            continue
        if line.startswith("#"):
            continue

        # If old format, check if first field matches IOC name
        # If new, check second field
        parts = line.split()
        if (format == 0 and parts[0] == iocName) or (format == 1 and parts[1] == iocName):
            return line

    return False


if __name__ == "__main__":
    from pprint import pprint
    iocInfos = parseScreenIOCs(sys.argv[1])
    pprint(iocInfos)
