#!/usr/bin/python
import re
import subprocess

import isi.app.lib.cluster as cluster
import isi.hw.bay as hwbay
import isi.hw.hal as hal
import isi.hw.ipmi as ipmi
import isi.sys.disk as disk
import isi.celog
from isi.celog.eventids import eventid_map

def main():
    # Filter out unsupported bootdisks and create an alert if necessary.
    #
    # HAL takes eligible boot disks and filters for only qualified devices.
    #
    # We should care deeply about whether the device is supported, as iffy boot
    # devices mean very bad things when they fail.
    #
    # EXCEPT for virtual nodes.  For that, we do not care :)
    mesh = disk.mesh 
    providers = filter(lambda x: x.name in hal.getEligibleBootdiskDeviceNames(),
                       mesh.disk_providers)
    if not hal.isVirtualNode():
        eligible_disks = hal.getSupportedEligibleBootdiskDeviceNames() 

        for provider in providers:
            # Calling bay2mfginfo should indicate whether or not the bay is alive.
            # If the bay is present but not alive, we should not be sending a
            # unsupported boot disk alert for it.
            bay = hwbay.dev2bay(provider.name)
            if hwbay.bay2mfginfo(bay) is None:
                continue
            if provider.name not in eligible_disks:
                try:
                    devid = int(cluster.Cluster().local_devid())
                except:
                    devid = None
                spec = { 'device' : provider.name }
                msg = ("Device {device} located at {location} is not a supported"
                       " boot disk. Please replace with a supported boot disk"
                       " immediately.")
                mev = isi.celog.Event(
                        event_id=eventid_map["SYS_DISK_BOOT_DISK_UNSUPPORTED"],
                        severity=isi.celog.EVENT_LEVEL_CRIT,
                        devid = devid,
                        message = msg,
                        specifier=spec)
                mev.add()
                # Add to BMC SEL
                sel_identifier = re.sub('\D+', '', provider.name)
                try:
                    sel_identifier = int(sel_identifier)
                except ValueError:
                    sel_identifier = 0
                hal.addSelEntry(isi.celog.EVENT_LEVEL_CRIT, ipmi.SEL_HW_COMP_BOOT_DRIVE,
                    sel_identifier, eventid_map["SYS_DISK_BOOT_DISK_UNSUPPORTED"])

        [op, err] = subprocess.Popen(['/usr/sbin/isi_bootdisk_type'],
	    stdout=subprocess.PIPE).communicate()
        if op.find('gmirror') != -1:
            import sys
            import isi.sys.bootdisk as bootdisk
            bootdisk.warn_if_one_bootdisk()

if __name__ == '__main__':
    main()
