'''
networkTree alarms module

Generate AlarmConfig-ntwk src files and build them.

joaoprod 2017

'''

import json
import utils
import os
import shutil
import datetime


def cleanOutputDir(outputDir,cleanOnlySaci=False):
    '''
    Clean alhConfig output directory
    :param outputDir:
    :return:
    '''

    now = os.getcwd()

    os.chdir(outputDir)
    folder = './'

    for the_file in os.listdir(folder):
        file_path = os.path.join(folder, the_file)
        try:
            if os.path.isfile(file_path):

                if cleanOnlySaci:
                    if file_path.split('/')[-1].find('networkTree_')==0 or file_path.split('/')[-1].find('saci_')==0:
                        os.unlink(file_path)
                else:
                    os.unlink(file_path)

        except Exception as e:
            print(e)
    os.chdir(now)

def getDevicesGroups(filtered_saci, label):
    '''
    Create alarms groups for devices in filtered_saci grouped by IOCs,CRATEs,CAMACs and ACWSs
    :param filtered_saci:
    :param label:
    :return:
    '''

    crates_group = dict(alias='Crates',
                        groupName="CRAT:" + label.upper(),
                        groups=[],
                        guidance='Crates summary')

    iocs_group = dict(alias='IOCs',
                      groupName="IOC:" + label.upper(),
                      groups=[],
                      guidance='IOCs summary')

    acsws_group = dict(alias='ACSWs',
                       groupName="ACSW:" + label.upper(),
                       groups=[],
                       guidance='ACSWs summary')

    camacs_group = dict(alias='CAMACs',
                        groupName="CAMC:" + label.upper(),
                        groups=[],
                        guidance='CAMACs summary')


    for object in filtered_saci.keys():

        if object.split(':')[0] in ['IOC', 'SIOC', 'VIOC', 'EIOC']:
            object = object.split(":")[0] + ':' + object.split(":")[1] + ':' + object.split(":")[2]

            ioc_group = dict(groupName=object + ':NW99',
                             PVs=[],
                             guidance=object + ' summary')

            for pv in filtered_saci[object]['alarms']['sumyPvs']:
                ioc_group['PVs'].append(pv)

            ioc_group['PVs'] = sorted(ioc_group['PVs'], key=lambda k: k['PVName'], reverse=True)
            iocs_group['groups'].append(ioc_group)

        elif object.split(':')[0] in ['ACSW']:
            object = object.split(":")[0] + ':' + object.split(":")[1] + ':' + object.split(":")[2]

            acsw_group = dict(groupName=object + ':NW99',
                              PVs=[],
                              guidance=object + ' summary')

            for pv in filtered_saci[object]['alarms']['sumyPvs']:
                acsw_group['PVs'].append(pv)

            acsw_group['PVs'] = sorted(acsw_group['PVs'], key=lambda k: k['PVName'], reverse=True)
            acsws_group['groups'].append(acsw_group)

        elif object.split(':')[0] in ['CRAT', 'CPU', 'MCOR', 'UPS']:

            object = object.split(":")[0] + ':' + object.split(":")[1] + ':' + object.split(":")[2]

            crate_group = dict(groupName=object + ':NW99',
                               PVs=[],
                               guidance=object + ' summary')

            for pv in filtered_saci[object]['alarms']['sumyPvs']:
                crate_group['PVs'].append(pv)

            crate_group['PVs'] = sorted(crate_group['PVs'], key=lambda k: k['PVName'], reverse=True)
            crates_group['groups'].append(crate_group)

        elif object.split(':')[0] in ['CAMC', 'CAMI']:

            camac_group = dict(groupName=object + ':NW99',
                               groups=[],
                               guidance=object + ' summary')

            groups = []
            for pv in filtered_saci[object]['alarms']['sumyPvs']:
                if ':'.join(pv['PVName'].split(':')[:-1]) not in groups:
                    groups.append(':'.join(pv['PVName'].split(':')[:-1]))

            for group in groups:
                sub_camac_group = dict(groupName=group + ':NW99',
                                       PVs=[],
                                       guidance=object + ' summary')

                for pv in filtered_saci[object]['alarms']['sumyPvs']:
                    if ':'.join(pv['PVName'].split(':')[:-1]) == group:
                        sub_camac_group['PVs'].append(pv)

                sub_camac_group['PVs'] = sorted(sub_camac_group['PVs'], key=lambda k: k['PVName'], reverse=True)
                camac_group['groups'].append(sub_camac_group)

            camac_group['groups'] = sorted(camac_group['groups'], key=lambda k: k['groupName'], reverse=True)
            camacs_group['groups'].append(camac_group)

        else:
            print ('Error : Device type not implemented: ' + object)

        camacs_group['groups'] = sorted(camacs_group['groups'], key=lambda k: k['groupName'], reverse=True)
        iocs_group['groups'] = sorted(iocs_group['groups'], key=lambda k: k['groupName'], reverse=True)
        acsws_group['groups'] = sorted(acsws_group['groups'], key=lambda k: k['groupName'], reverse=True)
        crates_group['groups'] = sorted(crates_group['groups'], key=lambda k: k['groupName'], reverse=True)

    groups = []

    if len(iocs_group['groups']):
        groups.append(iocs_group)
    if len(crates_group['groups']):
        groups.append(crates_group)
    if len(acsws_group['groups']):
        groups.append(acsws_group)
    if len(camacs_group['groups']):
        groups.append(camacs_group)

    groups = sorted(groups, key=lambda k: k['alias'], reverse=True)

    return groups

def getButtonsGroups(saci,filtered_saci):

    button_groups = []

    # Filter saci for subsystem buttons groups
    for object in filtered_saci.keys():

            if 'networkDisplay' in filtered_saci[object].keys():
                if filtered_saci[object]['networkDisplay']['active']:

                    # Filter saci for ioc button
                    filtered_networkTree_button = dict()

                    if 'legacy' in filtered_saci[object]['alarms']:
                        if filtered_saci[object]['alarms']['legacy']['active']:
                            for alarm in filtered_saci[object]['alarms']['legacy']['relatedAlarms']:
                                for type in saci.keys():
                                    if alarm in saci[type]:
                                        filtered_networkTree_button[alarm] = saci[type][alarm]

                    button_group = dict(groupName=object+':GROUP' ,
                                        groups=getDevicesGroups(filtered_networkTree_button, object + ':GROUP'),
                                        guidance=object+' Button summary')

                    button_group['groups'] = sorted(button_group['groups'], key=lambda k: k['groupName'], reverse=True)
                    button_groups.append(button_group)

    button_groups = sorted(button_groups, key=lambda k: k['groupName'], reverse=True)
    return button_groups

def generateAlarmsConfigs(outputDir,saci,config):
    '''
    Generate alhConfig files to the network area
    :param outputDir:
    :return:
    '''

    # List all areas
    areas=dict()
    areas_names = []
    for objects in saci.keys():
        for object in saci[objects].keys():
            if 'alarms' in saci[objects][object].keys():
                if saci[objects][object]['alarms']['active']:
                    area = saci[objects][object]['location']['area']
                    if area not in areas_names:
                        areas_names.append(area)
                        area_dict = utils.getAreaDetails(area)
                        areas[area] = area_dict

        network_file = dict(alias="NTWK_new",
                            groupName="ALL:NTWK_new:1",
                            guidance="networkTree alarms auto-generated tree.",
                            includes=[],
                            commands = ["$COMMAND networkTreeDisplay"]
                            )

    for area in areas:
        area_file = dict(alias=area.upper(),
                                    groupName="NTWK_new:"+area.upper()+':1',
                                    guidance=area.upper()+" Network",
                                    commands=["$COMMAND networkTreeDisplay -a "+area.upper()],
                                    includes=[]
                                    )

        area_subsys_file = dict(alias=area.upper()+" subsystems",
                                    groupName="NTWK_new:"+area.upper()+'SUBS'+':ALL',
                                    guidance=area.upper()+" Network Subsystems",
                                    commands=["$COMMAND networkTreeDisplay -a " + area.upper()],
                                    groups=[]
                                    )

        # List all the subsystems in the area
        subsystems = []
        for objects in saci.keys():
            for object in saci[objects].keys():
                if 'alarms' in saci[objects][object].keys():
                    if saci[objects][object]['alarms']['active']:
                        if 'location' in saci[objects][object].keys():
                            if 'area' in saci[objects][object]['location'].keys():
                                if saci[objects][object]['location']['area'] == area:
                                    if 'subsystem' in saci[objects][object].keys():
                                        subsystem = saci[objects][object]['subsystem']
                                        if subsystem not in subsystems:
                                            subsystems.append(subsystem)

        for subsystem in subsystems:

            # Filter saci for subsystem
            filtered_saci = dict()
            for objects in saci.keys():
                for object in saci[objects].keys():
                    if 'alarms' in saci[objects][object].keys():
                        if saci[objects][object]['alarms']['active']:
                            if saci[objects][object]['subsystem'] == subsystem and saci[objects][object]['location']['area'] == area:
                                filtered_saci[object] = saci[objects][object]

            subsystem_group = dict(alias=subsystem.upper(),
                                   groupName='NTWK_new:' + area.upper() + 'SUBS' + ':' + config['subsystems'][subsystem]['alarmCode'],
                                   guidance=area.upper() + ' ' + subsystem + ' summary.',
                                   #groups=getDevicesGroups(filtered_saci,area + 'SUBS:' + config['subsystems'][subsystem]['alarmCode']),
                                   groups=getButtonsGroups(saci,filtered_saci),
                                   commands=["$COMMAND networkTreeDisplay -a " + area.upper() + ' -s ' + subsystem],
                                   )

            area_subsys_file['groups'].append(subsystem_group)


        # Create area_subsys_file
        area_subsys_file['groups'] = sorted(area_subsys_file['groups'], key=lambda k: k['alias'], reverse = True)
        outputName = 'networkTree_ntwk_' + area.lower() + '_subsys'
        with open(outputDir + outputName + '.json', 'w') as outfile:
            res = json.dump(area_subsys_file, outfile, sort_keys=False, indent=1, separators=(',', ': '))
        os.system('jsonTOalhConfig.py ' + outputDir + outputName + '.json ' + outputDir + outputName + '.alhConfig')

        area_file['includes'].append('./'+outputName + '.alhConfig')

        area_subareas_file = dict(alias=area.upper()+" subareas",
                                    groupName="NTWK_new:"+area.upper()+"SUBA"+':ALL',
                                    guidance=area.upper()+" Subareas",
                                    commands=["$COMMAND networkTreeDisplay -a " + area.upper()],
                                    groups=[]
                                    )

        #Check for subareas
        subareas = []
        for objects in saci.keys():
            for object in saci[objects].keys():
                 if 'alarms' in saci[objects][object].keys():
                    if saci[objects][object]['alarms']['active']:
                        object_area = saci[objects][object]['location']['area']
                        if object_area == area:
                            if 'subArea' in saci[objects][object]['location']:
                                for subarea in saci[objects][object]['location']['subArea']:
                                    if subarea not in subareas:
                                        subareas.append(subarea)

        for subarea in subareas:

            # Filter saci for subarea
            filtered_saci = dict()
            for objects in saci.keys():
                if objects not in []:
                    for object in saci[objects].keys():
                        if 'alarms' in saci[objects][object].keys():
                            if saci[objects][object]['alarms']['active']:
                                if 'area' in saci[objects][object]['location'].keys() and 'subArea' in saci[objects][object]['location'].keys():
                                    if subarea in saci[objects][object]['location']['subArea']:
                                        filtered_saci[object] = saci[objects][object]
                                        if 'legacy' in saci[objects][object]['alarms']['legacy']:
                                            if saci[objects][object]['alarms']['legacy']['alarms']['active']:
                                                for alarm in saci[objects][object]['alarms']['legacy']['alarms']:
                                                    if alarm not in filtered_saci:
                                                        for type in saci.keys():
                                                            if alarm in saci[type]:
                                                                filtered_saci[alarm] = saci[type][alarm]

            subarea_group = dict( alias=subarea.upper(),
                                   groupName='NTWK_new:'+ area.upper() +'SUBA:'+subarea.upper(),
                                   guidance = area.upper() + ' ' + subarea.upper() + ' summary',
                                   #groups = getDevicesGroups(filtered_saci,(area+'SUBA:'+subarea).upper()),
                                   groups=getDevicesGroups(filtered_saci, (area + 'SUBA:' + subarea).upper()),
                                   commands = ["$COMMAND networkTreeDisplay -a " + area.upper()])

            if len(subarea_group['groups']):
                area_subareas_file['groups'].append(subarea_group)

        if len(area_subareas_file['groups']):

            # Create area_subareas_file
            area_subareas_file['groups'] = sorted(area_subareas_file['groups'], key=lambda k: k['alias'], reverse = True)
            outputName = 'networkTree_ntwk_' + area.lower() + '_subareas'
            with open(outputDir + outputName + '.json', 'w') as outfile:
                res = json.dump(area_subareas_file, outfile, sort_keys=False, indent=1, separators=(',', ': '))
            os.system('jsonTOalhConfig.py ' + outputDir + outputName + '.json ' + outputDir + outputName + '.alhConfig')

            area_file['includes'].append('./'+outputName + '.alhConfig')

        # Create area_file
        area_file['includes'] = sorted(area_file['includes'])
        outputName = 'networkTree_ntwk_' + area.lower()
        with open(outputDir + outputName + '.json', 'w') as outfile:
            res = json.dump(area_file, outfile, sort_keys=False, indent=1, separators=(',', ': '))
        os.system('jsonTOalhConfig.py ' + outputDir + outputName + '.json ' + outputDir + outputName + '.alhConfig')

        network_file['includes'].append('./'+outputName + '.alhConfig')

    # Create network_file
    network_file['includes'] = sorted(network_file['includes'])
    outputName = 'networkTree_ntwk'
    with open(outputDir + outputName + '.json', 'w') as outfile:
        res = json.dump(network_file, outfile, sort_keys=False, indent=1, separators=(',', ': '))
    os.system('jsonTOalhConfig.py ' + outputDir + outputName + '.json ' + outputDir + outputName + '.alhConfig')



    # Include networkTree_ntwk in ntwk
    outputName = 'ntwk'

    os.system('alhConfigTOjson.py ' + outputDir + outputName + '.alhConfig ' + outputDir + outputName + '.json')

    with open(outputDir+'ntwk.json') as file:
        main_network_file = json.load(file)

    if './networkTree_ntwk.alhConfig' not in main_network_file['includes'] and 'networkTree_ntwk.alhConfig' not in main_network_file['includes'] :
        main_network_file['includes'].append('./networkTree_ntwk.alhConfig')

    if './saci_ntwk.alhConfig' in main_network_file['includes']:
        main_network_file['includes'].remove('./saci_ntwk.alhConfig')

    if 'saci_ntwk.alhConfig' in main_network_file['includes']:
        main_network_file['includes'].remove('saci_ntwk.alhConfig')

    network_file['includes'] = sorted(network_file['includes'])
    with open(outputDir + outputName + '.json', 'w') as outfile:
        res = json.dump(main_network_file, outfile, sort_keys=False, indent=1, separators=(',', ': '))
    os.system('jsonTOalhConfig.py ' + outputDir + outputName + '.json ' + outputDir + outputName + '.alhConfig')

def generateAlarms(saciPath, configPath, restartIocCommand = None, cleanOutput=False, testALHTree=False,
                    makeAlarms=False, restartIoc=False,cleanSaciOutput=True, generate = True, commit =False, release = False,
                    change_prod_dev_soft_link = False, release_name = None):
    '''
    Driving function to auto-generate alarms
    :param iocConfigFacility:
    :param cleanOutput:
    :param testALHTree:
    :param makeAlarms:
    :param restartIoc:
    :return:
    '''

    original_release = 'MAIN_TRUNK'

    os.system('source $TOOLS/AlarmConfigsTop/SCRIPT/AlarmEnvSetup.bash')


    utils.readConfigs(configPath)

    # Import networkTree data
    print ('Opening networkTree network file: '+ saciPath)
    with open(saciPath) as file:
        saci = json.load(file)

    # Import networkTree config
    print ('Opening networkTree config file: ' + configPath)
    with open(configPath) as file:
        config = json.load(file)

    home = os.getcwd()
    output = 'output/'
    rep = original_release+'/'
    rep_source = rep+'lcls/src/'

    # Clean output dir
    try:
        shutil.rmtree(output)
    except:
        pass

    try:
        os.makedirs(output)
    except:
        pass


    print ("Cheking out AlarmConfigs-ntwk from CVS.")
   # os.system("cvs co AlarmConfigs-ntwk")

    os.system('cvs co -d ' + original_release + ' AlarmConfigs-ntwk')

    # Copy from rep to output
    for file in os.listdir(rep_source):
        try:
            shutil.copyfile(rep_source+file,output+file)
        except:
            pass

    if cleanOutput:
        print ("Cleaning src directory: " + output)
        cleanOutputDir(output)

    if cleanSaciOutput:
        print ("Cleaning networkTree files in the src directory: " + output)
        cleanOutputDir(output,cleanOnlySaci=True)


    if generate:
        print ("Generating new alhConfig files.")
        generateAlarmsConfigs(output,saci,config)

        os.chdir(output)
        for file in os.listdir('./'):
            if file.split('.')[-1] == 'json':
                os.remove(file)
        os.chdir(home)

    if testALHTree:
        print ("Testing new ALH tree.")
        os.chdir(output)
        print ("Please close the ALH GUI when you are ready to proceed.")

        os.system('testALHTree.bash ntwk.alhConfig')

        try:
            input = raw_input
        except NameError:
            pass
        user = input("Is the alarm tree ok? Proceed? (y/n): ")

        ok = str(user).upper() == 'Y' or str(user).upper == 'YES'
        os.chdir(home)
        if not ok:
            print ('Aborting.')
            shutil.rmtree(rep)
            return

    for file in os.listdir(rep_source):
        if file not in os.listdir(output):
            try:
                os.remove(rep_source+file)
                os.system('cvs remove ' + rep_source+file)
            except:
                pass

    # Copy from rep to output
    for file in os.listdir(output):
        try:
            shutil.copyfile(output+file,rep_source+file)
            os.system('cvs add ' + rep_source + file)
        except:
            pass




    if release:
        os.chdir(rep)

        notes = ("{} LCLS  {} networkTree alarm configs auto-generation \n \t\t Auto-generated networkTree alarm tree based on networkTreeConfig {}.\n\n").format(release_name,datetime.date.today().strftime('%d-%b-%Y'),saciPath.split('/')[-3])

        shutil.move("RELEASE_NOTES", "RELEASE_NOTES_old")

        f = open('RELEASE_NOTES_old', 'r')
        newf = open('RELEASE_NOTES', 'w')
        lines = f.readlines()  # read old content
        newf.write(notes)  # write new content at the beginning
        for line in lines:  # write old content after new
            newf.write(line)
        newf.close()
        f.close()

        os.remove("RELEASE_NOTES_old")

        os.system("cvs commit -m 'New auto-generated networkTree alarm tree based on networkTreeConfig " + saciPath.split('/')[-3] + ".'")

        release_name = release_name
        os.system ('cvs tag '+ release_name)

        os.chdir(home)

	print ('Updating $TOOLS/AlarmConfigsTop/ntwk')
	os.chdir(os.environ['TOOLS']+'/AlarmConfigsTop/ntwk')
	if release_name not in os.listdir('./'):
        	os.system('cvs co -d '+  release_name +' -r '+ release_name + ' AlarmConfigs-ntwk')
	
    else:
        if commit:
            print ("Commiting to CVS")
            os.chdir(rep)
            os.system(
                "cvs commit -m 'New auto-generated networkTree alarm tree based on networkTreeConfig " + saciPath.split('/')[-3] + ".'")
            os.chdir(home)
        release_name = original_release
	
	print ('Updating $TOOLS/AlarmConfigsTop/ntwk')
	os.chdir(os.environ['TOOLS']+'/AlarmConfigsTop/ntwk/'+original_release)
	os.system('cvs update')

    print ('Updating $TOOLS/AlarmConfigsTop/ntwk')

    if change_prod_dev_soft_link:
        print ('Changing prod softlink to: '+release_name)
	os.chdir(os.environ['TOOLS']+'/AlarmConfigsTop/ntwk/')
        os.remove('prod')
        os.system('ln -s '+release_name+' prod')

    release_source_path = os.environ['TOOLS']+'/AlarmConfigsTop/ntwk/'+release_name+'/lcls/src'
    os.chdir(release_source_path)

    if makeAlarms:
        print("Make alarms on: "+release_source_path)
        os.system('makeAlarms.bash lcls ntwk')

    if restartIoc and (restartIocCommand is not None):
        print ("Restarting the alarm ioc.")
        os.system(restartIocCommand)
        # ssh laci@lcls-dev1 /etc/init.d/st.sioc-alh0-ntwk00 restart

    print ('Cleaning up.')
    os.chdir(home)
    shutil.rmtree(rep)


def generateAlarmsMasterDev():

    abspath = os.path.abspath(__file__)
    dname = os.path.dirname(abspath)
    os.chdir(dname)

    saciPath = os.path.expandvars('/$TOOLS/script/'+os.readlink(os.path.expandvars('/$TOOLS/script/networkTreeConfig'))+'/../networkTreeConfig-git/data/networkTree.json')
    configPath = os.path.expandvars('/$TOOLS/script/'+os.readlink(os.path.expandvars('/$TOOLS/script/networkTreeConfig'))+'/../networkTreeConfig-git/config/config.json')
    cleanOutput = False
    cleanSaciOutput = True
    generate = True
    testALHTree = True
    commit = True
    release = False
    release_name = 'MAIN_TRUNK'
    change_prod_dev_soft_link = True
    makeAlarms = True
    restartIoc = True
    restartIocCommand = 'ssh laci@lcls-dev1 /etc/init.d/st.sioc-alh0-ntwk00 restart'


    generateAlarms(saciPath=saciPath, configPath=configPath, restartIocCommand=restartIocCommand, cleanOutput=cleanOutput, testALHTree=testALHTree,
                    makeAlarms=makeAlarms, restartIoc=restartIoc,cleanSaciOutput=cleanSaciOutput, generate = generate, commit =commit, release = release,
                    change_prod_dev_soft_link = change_prod_dev_soft_link, release_name = release_name)

def generateAlarmsReleaseDev():

    abspath = os.path.abspath(__file__)
    dname = os.path.dirname(abspath)
    os.chdir(dname)

    saciPath = os.path.expandvars('/$TOOLS/script/'+os.readlink(os.path.expandvars('/$TOOLS/script/networkTreeConfig'))+'/data/networkTree.json')
    configPath = os.path.expandvars('/$TOOLS/script/'+os.readlink(os.path.expandvars('/$TOOLS/script/networkTreeConfig'))+'/config/config.json')
    cleanOutput = False
    cleanSaciOutput = True
    generate = True
    testALHTree = True
    commit = True
    release = True

    release_name = "AlarmConfigs-ntwk-"+os.readlink(os.path.expandvars('$TOOLS/script/networkTreeConfig')).split('/')[-1].replace(".","-")+"-0"

    change_prod_dev_soft_link = True
    makeAlarms = True
    restartIoc = False
    restartIocCommand = 'ssh laci@lcls-dev1 /etc/init.d/st.sioc-alh0-ntwk00 restart'


    generateAlarms(saciPath=saciPath, configPath=configPath, restartIocCommand=restartIocCommand, cleanOutput=cleanOutput, testALHTree=testALHTree,
                    makeAlarms=makeAlarms, restartIoc=restartIoc,cleanSaciOutput=cleanSaciOutput, generate = generate, commit =commit, release = release,
                    change_prod_dev_soft_link = change_prod_dev_soft_link, release_name = release_name)

def updateProd():

    release_name = "AlarmConfigs-ntwk-" + os.readlink(os.path.expandvars('$TOOLS/script/networkTreeConfig')).split('/')[-1].replace(".", "-") + "-0"

    os.chdir(os.environ['TOOLS'] + '/AlarmConfigs/ntwk')

    if release_name not in os.listdir('./'):

	print    ('cvs co -d ' + release_name + ' -r ' + release_name + ' AlarmConfigs-ntwk')
        os.system('cvs co -d ' + release_name + ' -r ' + release_name + ' AlarmConfigs-ntwk')

    print ('Changing prod softlink to: ' + release_name)
    os.remove('prod')
    os.system('ln -s ' + release_name + ' prod')

    release_source_path = os.environ['TOOLS'] + '/AlarmConfigsTop/ntwk/' + release_name + '/lcls/src'
    os.chdir(release_source_path)

    print("Make alarms on: " + release_source_path)
    os.system('makeAlarms.bash lcls ntwk')

    print ("Restarting the alarm IOC.")
    restartIocCommand = 'ssh laci@lcls-daemon1 /etc/init.d/st.sioc-alh0-ntwk00 restart'
    os.system(restartIocCommand)

    print ("Restarting the alarm daemon.")
    restartIocCommand = 'ssh laci@lcls-daemon2 /etc/init.d/st.alh-ntwk restart'
    os.system(restartIocCommand)

def updateDev():

    release_name = "AlarmConfigs-ntwk-" + os.readlink(os.path.expandvars('$TOOLS/script/networkTreeConfig')).split('/')[-1].replace(".", "-") + "-0"

    os.chdir(os.environ['TOOLS'] + '/AlarmConfigs/ntwk')

  #  if release_name not in os.listdir('./'):
    print ('cvs co -d ' + release_name + ' -r ' + release_name + ' AlarmConfigs-ntwk')
    os.system('cvs co -d ' + release_name + ' -r ' + release_name + ' AlarmConfigs-ntwk')

    print ('Changing prod softlink to: ' + release_name)
    os.remove('prod')
    os.system('ln -s ' + release_name + ' prod')

    release_source_path = os.environ['TOOLS'] + '/AlarmConfigsTop/ntwk/' + release_name + '/lcls/src'
    os.chdir(release_source_path)

    print("Make alarms on: " + release_source_path)
    os.system('makeAlarms.bash lcls ntwk')

    print ("Restarting the alarm IOC.")
    restartIocCommand = 'ssh laci@lcls-dev1 /etc/init.d/st.sioc-alh0-ntwk00 restart'
    os.system(restartIocCommand)

# ----------------------------------------------------------------------
if __name__ == "__main__":
    generateAlarmsMasterDev()





