#!/usr/bin/env python
"""Parser for parsing iocShell include commands
These take these forms
1) < envPaths
2) < iocBoot/${IOC}/areaDetector.cfg
3) < config/epicsEnvSetDev
4) < /boot/u/ad/mboyes/work/work-EPM/iocBoot/ioctest/pre_st.cmd
5) < "../st.padgeneric.cmd"
6) < /reg/d/iocCommon/All/pre_linux.cmd
7) . "../st.fnetgeneric.lcls.cmd"
8) . "iocBoot/start_restore.cmd"
"""
from __future__ import print_function

import re

# Form regex patterns for the four possible forms
includePatterns = []
patternComponentLists = [
    ['<+', r'"([^"]+)"'],  # < "../st.padgeneric.cmd"
    ['<+', r'(\S+)'],      # < envPaths
    ['. ', r'"([^"]+)"'],  # . "../st.fnetgeneric.lcls.cmd"
    ['. ', r'(\S+)'],      # . iocBoot/start_restore.cmd
]
for patternComponents in patternComponentLists:
    # Allow spaces between components and comments at the end
    pattern = r'^\s*{}\s*(?:#.*)?$'.format(r'\s*'.join(patternComponents))
    includePatterns.append(re.compile(pattern))

def multiRegexMatch(regexPatterns, text):
    '''Matches text against multiple regex patterns'''
    for pattern in regexPatterns:
        result = pattern.match(text)
        if result:
            return result

    return None

def parseIncludeCommand(line):
    '''Parses a epics include command and returns the file name we are including'''
    result = multiRegexMatch(includePatterns, line)
    if result:
        return result.group(1)

    return line

"""Parser for parsing iocShell include commands
These take these forms
1) 
2) 
3) 
4) 
5) 
"""


if __name__ == "__main__":
    print('|' + parseIncludeCommand('< envPaths') + '|')
    print('|' + parseIncludeCommand('< iocBoot/${IOC}/areaDetector.cfg') + '|')
    print('|' + parseIncludeCommand('< config/epicsEnvSetDev') + '|')
    print('|' + parseIncludeCommand('< /boot/u/ad/mboyes/work/work-EPM/iocBoot/ioctest/pre_st.cmd') + '|')
    print('|' + parseIncludeCommand('< "../st.padgeneric.cmd"') + '|')
    print('|' + parseIncludeCommand('< /reg/d/iocCommon/All/pre_linux.cmd') + '|')
    print('|' + parseIncludeCommand('</usr/local/lcls/epics/iocCommon/All/Prod/soft_pre_st.cmd') + '|')
    print('|' + parseIncludeCommand('< iocBoot/ioc-und1-uc24/st-unique.cmd') + '|')
    print('|' + parseIncludeCommand('< ../../common/init_st.soft.cmd') + '|')
    print('|' + parseIncludeCommand('< ${TOP}/iocBoot/st.softgeneric.cmd') + '|')
    print('|' + parseIncludeCommand('< ${AREA_DETECTOR}/iocBoot/commonPlugins.cmd') + '|')
    print('|' + parseIncludeCommand('<<<<<< st.cmd') + '|')
    print('|' + parseIncludeCommand('. "../st.fnetgeneric.lcls.cmd"') + '|')
    print('|' + parseIncludeCommand('. "iocBoot/start_restore.cmd"') + '|')
    print('|' + parseIncludeCommand('. iocBoot/start_restore.cmd') + '|')
    
