#!/usr/bin/python
import sys
import socket
from raid import raid
import re
import os
from subprocess import PIPE, Popen
hostname = socket.gethostname()

def check_software_raid():
    if os.path.exists('/proc/mdstat'):
        lines = [ x for x in open('/proc/mdstat','r') if x.find('blocks')>0 ]
        if len(lines) == 0:
            return 1
        if len([ x for x in lines if x.find('[UU]') == -1]):
            return 0
    return 1

if not os.path.exists("/usr/local/eig_zabbix/tmp"):
    os.makedirs("/usr/local/eig_zabbix/tmp")

f = open("/usr/local/eig_zabbix/tmp/raid.tmp", 'w')

f.write("%s %s %s\n" % (hostname, 'raid["AbortedCommands"]', raid.get_total_aborted_commands()))
f.write("%s %s %s\n" % (hostname, 'raid["Battery"]', raid.is_battery_good()))
f.write("%s %s %s\n" % (hostname, 'raid["FailedStripes"]',  raid.has_failed_stripes()))
f.write("%s %s %s\n" % (hostname, 'raid["FirmwareState"]',  raid.is_optimal()))
f.write("%s %s %s\n" % (hostname, 'raid["MediaErrors"]', raid.get_total_media_errors()))
f.write("%s %s %s\n" % (hostname, 'raid["MaxMediaErrors"]', raid.get_max_media_errors()))
f.write("%s %s %s\n" % (hostname, 'raid["OfflineSectors"]', raid.get_total_smart("offilne_uncorrectable")))
f.write("%s %s %s\n" % (hostname, 'raid["ReallocatedSectors"]', raid.get_total_smart("reallocated_sector_ct")))
f.write("%s %s %s\n" % (hostname, 'raid["SmartErrors"]', raid.get_total_smart("smart_errors")))
f.write("%s %s %s\n" % (hostname, 'raid["UDMACRC"]', raid.get_total_smart("udma_crc_errors")))
f.write("%s %s %s\n" % (hostname, 'raid["UncorrectedReads"]', raid.get_total_smart("uncorrected_read")))
f.write("%s %s %s\n" % (hostname, 'raid["UncorrectedWrites"]', raid.get_total_smart("uncorrected_write")))
f.write("%s %s %s\n" % (hostname, 'raid["PredictiveFailure"]', raid.predictivefailure()))
f.write("%s %s %s\n" % (hostname, 'raid["SoftwareRaidStatus"]', check_software_raid()))
f.write("%s %s %s\n" % (hostname, 'raid["CachecadeOff"]', raid.is_cached_enabled_and_on()))

f.close()

Popen(["/usr/local/eig_zabbix/sbin/raidcheck/raid/ssdlife"]).communicate()

zabbix_regex = re.compile('ServerActive\s*=\s*([a-zA-Z0-9\.-]+)')

f = open("/etc/zabbix/zabbix_agentd.conf","r")
zabbix_server="zabbix3.hou1.endurance.com"
for line in f.readlines():
    line_match = re.match(zabbix_regex, line)
    if line_match:
        zabbix_server =  line_match.group(1)

Popen(["/usr/bin/zabbix_sender", "-z", zabbix_server, "-i", "/usr/local/eig_zabbix/tmp/raid.tmp" ]).communicate()
