#!/usr/bin/env python
'''This is the backend for iocDetails.html - a web page that serves out info about deployed IOC's, their packages and versions.
We look in ${EPICS_IOCS} for the list if IOCSs, use the iocSpecificRelease and screeniocs file to determine various aspects of the IOCs and serve that out as a web page,
For now, there are three sections
1) IOCs - This gives you a list of SIOC's and HIOC's; the package and their current version.
2) CPUs - This gives us a list of linuxRT CPUs and the VIOC's that run on each of these CPU's
3) Unknown - Not all IOC's were converted to cram; so this contains a list of IOC's using the legacy startup scripts. These should be converted to cram  to facilitate scripts like this one.
 '''

import os
import ujson
import logging
from bottle import route, run, request, abort, Bottle, static_file
from gevent import monkey; monkey.patch_all()
import collections


app = Bottle()

logger = logging.getLogger("iocDetails")
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
handler = logging.StreamHandler()
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.setLevel(logging.DEBUG)


@app.route('/iocDetails/iocs')
def iocList():
    '''Determine the IOCs in this facility based on the value of the EPICS_IOCS environment variable'''
    iocCommon = os.environ['EPICS_IOCS']
    iocTop = os.path.realpath(os.environ['EPICS_IOC_TOP'])
    iocInfos = []
    iocCommonFiles = os.listdir(iocCommon)
    for iocname in sorted(iocCommonFiles):
        if os.path.isdir(os.path.join(iocCommon, iocname)):
            iocSpecificRelease = os.path.join(iocCommon, iocname, "iocSpecificRelease")
            if not os.path.exists(iocSpecificRelease):
                logger.warning("iocSpecificRelease does not exist for %s", iocname)
                continue
            iocInfo = { "name" : iocname }
            iocInfos.append(iocInfo)
            if not os.path.islink(iocSpecificRelease):
                logger.error("iocSpecificRelease is not a link for %s", iocname)
                iocInfo['package'] = 'N/A'
                iocInfo['version'] = 'N/A'
                iocInfo['st.cmd'] = 'N/A'
                continue
            linkTarget = os.path.realpath(iocSpecificRelease)
            if linkTarget.startswith(iocTop):
                linkTarget = linkTarget.replace(iocTop, "${EPICS_IOC_TOP}")
            version = os.path.basename(linkTarget)
            packageName = os.path.basename(os.path.dirname(linkTarget))
            iocInfo['package'] = packageName
            iocInfo['version'] = version
            iocInfo['st.cmd'] = os.path.join(linkTarget, 'iocBoot', iocname, 'st.cmd')
    return ujson.dumps(iocInfos)

@app.route('/iocDetails/cpus')
def cpuList():
    '''Determine the CPU's in this facility that run VIOC's'''
    logger.debug("Gathering the list of CPUs in this facility");
    iocCommon = os.environ['EPICS_IOCS']
    iocInfos = []
    iocCommonFiles = os.listdir(iocCommon)
    for iocname in sorted(iocCommonFiles):
        if os.path.isdir(os.path.join(iocCommon, iocname)) and iocname.startswith('cpu-'):
            iocInfo = { "name" : iocname }
            iocInfo['iocs'] = determineVIOCCPUDetails(iocname, iocInfo)
            iocInfos.append(iocInfo)
    return ujson.dumps(iocInfos)


@app.route('/iocDetails/unknowns')
def unknownList():
    '''IOCs with issues - these are non-CPU's that do not have a iocSpecificRelease'''
    logger.debug("Gathering the list of IOC's with issues in this facility");
    iocCommon = os.environ['EPICS_IOCS']
    iocInfos = []
    iocCommonFiles = os.listdir(iocCommon)
    for iocname in sorted(iocCommonFiles):
        if os.path.isdir(os.path.join(iocCommon, iocname)):
            if iocname.startswith('cpu-'):
                continue
            iocSpecificRelease = os.path.join(iocCommon, iocname, "iocSpecificRelease")
            if not os.path.exists(iocSpecificRelease):
                iocInfo = { "name" : iocname }
                iocInfos.append(iocInfo)
    return ujson.dumps(iocInfos)


def determineVIOCCPUDetails(cpuName, cpuInfo):
    '''Determine the IOC's that run on a CPU using screenIOC's, LOCAL_IOCS and softlinks in the IOC_COMMON/cpuName folder'''
    print "Determining the details for CPU", cpuName
    # See if the EPICS_IOCS/cpuName/startup.cmd is a softlink to a skel startup file; if so, we know not to parse the startup.cmd to determine LOCAL_IOCS,
    viocsInfo = []
    iocCommon = os.environ['EPICS_IOCS']
    startupCmd = os.path.join(iocCommon, cpuName, 'startup.cmd')
    if os.path.islink(startupCmd):
        if "skel/startup_cpu.cmd" not in os.path.realpath(startupCmd):
            msg = "The startup.cmd for {0} is a softlink but does not point to the standard skeleton startup file".format(cpuName)
            logger.debug(msg)
            cpuInfo["reasonForEmptiness"] = msg
            return viocsInfo
        logger.debug("The startup.cmd for %s is a softlink; using screenIocs to determine the IOC's that will be started on this CPU.", cpuName)
        screenIOCSFileName = os.path.join(iocCommon, "screeniocs")
        with open(screenIOCSFileName, 'r') as f:
            lines = f.readlines()
        viocNames = []
        for line in lines:
            line = line.strip()
            # Skip commented lines
            if line.startswith("#"):
                continue
            if cpuName in line:
                # Skip the line for the CPU itself
                if line.startswith(cpuName):
                    continue
                parts = line.split()
                if parts[1] == cpuName:
                    logger.debug("%s runs on %s", parts[0], cpuName)
                    viocNames.append(parts[0]);
        if not viocNames:
            msg = "ScreenIOCs does not have any IOC definitions for CPU {0}".format(cpuName)
            logger.debug(msg)
            cpuInfo["reasonForEmptiness"] = msg
            return viocsInfo
            
        for vioc in sorted(viocNames):
            logger.debug("Gathering details for %s", vioc)
            viocInfo = { "name" : vioc}
            viocsInfo.append(viocInfo)
            if not os.path.exists(os.path.join(iocCommon, vioc, "iocSpecificRelease")):
                print "iocSpecificRelease does not exist for ", vioc
                viocInfo['package'] = 'N/A'
                viocInfo['version'] = 'N/A'
                viocInfo['st.cmd'] = 'N/A'
                continue
            if not os.path.islink(os.path.join(iocCommon, vioc, "iocSpecificRelease")):
                print "iocSpecificRelease is not a link for ", vioc
                viocInfo['package'] = 'N/A'
                viocInfo['version'] = 'N/A'
                viocInfo['st.cmd'] = 'N/A'
                continue
            linkTarget = os.path.realpath(os.path.join(iocCommon, vioc, "iocSpecificRelease"))
            version = os.path.basename(linkTarget)
            packageName = os.path.basename(os.path.dirname(linkTarget))
            viocInfo['package'] = packageName
            viocInfo['version'] = version
            viocInfo['st.cmd'] = os.path.join(linkTarget, 'iocBoot', vioc, 'st.cmd')
    else:
        logger.debug("The startup.cmd for %s is not a softlink", cpuName)
        msg = "The startup.cmd for CPU {0} is not a softlink. This utility does not have the ability to parse local startup.cmd overwrites yet".format(cpuName)
        logger.debug(msg)
        cpuInfo["reasonForEmptiness"] = msg
        return viocsInfo

    return viocsInfo


if __name__ == "__main__":
    logger.error("Please use launcher.py to host all these utilities in a single gunicorn instance.")
