#!/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 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}".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

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