#!/usr/local/bin/python
import commands
import os
import re
import sys
import shutil
import time

import isi.hw.bootstrap as bootstrap
import isi.app.lib.procs as procs
import isi.hw.fw.modules.epost as epost

# TODO
# Dump extended battery status

copy_info = {}

def width(val):
    return len(str(val))

def max_width(values):
    return max(map(width, values))

def run_ipmiutil(netfn, lun, cmd, data):
    result = 0
    res_data = []
    # bus - 00
    # rsSa - 20
    # NetFn/lun - (NetFN << 2 || lun)
    # cmd
    netfn_lun = hex(netfn << 2 | lun).lstrip("0x")
    cmd = "/usr/bin/ipmiutil cmd 00 20 %s %s %s" % (netfn_lun, cmd, data)
    response_regex = re.compile("respData.*:\s+(?P<data>.*)")
    error, output = procs.get_cmd_output(cmd)
    if error:
        result = 1
    else:
        for line in output:
            match = response_regex.match(line)
            if match:
                res_data = match.group("data").strip(' ').split(' ')
                break
    return (result, res_data)

################# BBU CODE ###################

EXTENDED_STATUS_MAPPING = [
    # (name, starting offset, ending offset, convert?, conversion unit, units, default val)
    ('Status' , 1, 2, False, None, None, None),
    ('BIST result' , 3, 4, False, None, None, None),
    ('Self test results' , 5, 6, False, None, None, None),
    ('Fault state' , 7, 7, False, None, None, None),
    ('watchdog reset count' , 8, 8, False, None, None, None),
    ('Battery faults' , 9, 9, False, None, None, None),
    ('State of charge' , 10, 10, True, 1, "%", None),
    ('Discharge cycle Count' , 11, 12, True, 0.1, "cycles", None),
    ('Service life' , 13, 14, True, 1, "days", None),
    ('Unpowered storage life' , 15, 16, True, 1, "days", None),
    ('Battery ESR' , 17, 18, True, 0.1, "mOhms", None),
    ('Battery leakage current' , 19, 20, True, 0.1, "mA", None),
    ('Input faults' , 21, 21, False, None, None, None),
    ('Input voltage' , 22, 23, True, 0.01, "V", None),
    ('Input current' , 24, 25, True, 0.01, "A", None),
    ('Internal rail faults' , 26, 26, False, None, None, None),
    ('Internal rail voltage' , 27, 28, True, 0.01, "V", None),
    ('Internal rail current' , 29, 30, True, 0.01, "A", None),
    ('Battery output faults' , 31, 31, False, None, None, None),
    ('Battery output voltage' , 32, 33, True, 0.01, "V", None),
    ('Battery output current' , 34, 35, True, 0.01, "A", None),
    ('Temperature Faults' , 36, 36, False, None, None, None),
    ('Temperature 0' , 37, 38, True, 0.01, "C", None),
    ('Temperature 1 Faults' , 39, 39, False, None, None, None),
    ('Temperature 1' , 40, 41, True, 0.01, "C", None),
    ('Temperature 2 Faults' , 42, 42, False, None, None, None),
    ('Temperature 2' , 43, 44, True, 0.01, "C", None),
    ('Sense line voltage' , 45, 46, True, 0.01, "V", None),
    ('Sense line adjustment' , 47, 48, True, 0.01, "V", None),
    ('Cell faults/warnings' , 49, 50, False, None, None, None),
    ('Cell 0 voltage' , 51, 52, True, 0.01, "V", None),
    ('Cell 1 voltage' , 53, 54, True, 0.01, "V", None),
    ('Cell 2 voltage' , 55, 56, True, 0.01, "V", None),
    ('Cell 3 voltage' , 57, 58, True, 0.01, "V", None),
    ('Cell 4 voltage' , 59, 60, True, 0.01, "V", None),
    ('Cell 5 voltage' , 61, 62, True, 0.01, "V", None),
    ('Cell 6 voltage' , 63, 64, True, 0.01, "V", None),
    ('Cell 7 voltage' , 65, 66, True, 0.01, "V", None),
    ('State of health' , 67, 67, True, 1, "%", None),
    ('Storage capacity' , 68, 69, True, 0.01, "WHr", None),
    ('Deliverable capacity' , 70, 71, True, 0.01, "WHr", None),
    ('Regulator discharge current' , 72, 73, True, 0.01, "A", None),
    ('Regulator charge current' , 74, 75, True, 0.01, "A", None),
    ('Time to full of charge' , 76, 77, True, 1/3600.0, "hours", 0xFFFF),
    ('Time to empty' , 78, 79, True, 1/3600.0, "hours", 0xFFFF),
]

ipmitool = "/usr/local/bin/amd64-portbld-freebsd7.1-ipmitool raw"

# Phobos Functional Specification Section 6.13.1
BMC_NETFN = 0x30
BMC_CMD = 0xb0

# Phobos Functional Specification Section 7.3.6
BBU_FRU = 0x09
BBU_DEV = 0x03
BBU_IDX = 0x00

def getipmi( cmd ):
    """Executes a command and returns the space-delimited output as a list"""
    a = commands.getoutput(cmd)
    a = a.replace("\n","")
    a = a.replace("\r","")
    a = a.strip()
    vs = a.split(" ")
    return vs

def getipmi_bridged(page, command, bytes_rd, wr_bytes):
    """Returns a bridged IPMI command to the BCC"""
    if wr_bytes != []:
        add_cksum = True
    else:
        add_cksum = False
    cp_bmc = " 0x%02x 0x%02x" % (BMC_NETFN, BMC_CMD)
    cp_bbu = (" 0x%02x 0x%02x 0x%02x" % (BBU_FRU, BBU_DEV, BBU_IDX))
    pmb_ptr = 0xff     # PMBus pointer is not used
    # compute checksum for the command and any write bytes
    if add_cksum:
        cksum = command
        for i in wr_bytes:
            cksum += i
        wr_bytes.append(256 - (cksum % 256))

    b_ch = []
    for b in wr_bytes:
        b_ch.append("0x%02x" % b)
    wr_str = ' '.join(b_ch)
    cp_cmd = (" 0x%02x 0x%02x 0x%02x 0x%02x %s" %
        (page, pmb_ptr, bytes_rd, command, wr_str))
    cmd = ipmitool + cp_bmc + cp_bbu + cp_cmd
    vs = getipmi(cmd)
    return vs

def batt_cli(cmd):
    """Send cmd to BCC CLI"""
    cmd_list = []
    for ch in cmd:
        cmd_list.append(ord(ch))
    # Pad nulls to 30 bytes (chskum to be added later)
    for i in range (30 - len(cmd_list)):
        cmd_list.append(0)
    # Snoop and remove any stale buffer
    while True:
        vs = getipmi_bridged(0x07, 0x75, 0xbe, [])
        if (vs[2] == '00'):
            break
    # BCC Command insert
    # 0x0 bytes from Page 7 Command 0x74
    vs = getipmi_bridged(0x07, 0x74, 0x0, cmd_list)
    # Snoop the CLI
    zero_count = 0
    total_count = 0
    chrs = []
    while True:
        # BCC CLI Buffer Snoop
        # 0xbe bytes from Page 0x7 Command 0x75
        vs = getipmi_bridged(0x07, 0x75, 0xbe, [])
        # Payload length is two bytes
        if (vs[2] == '00' and vs[3] == '00'):
            # If there is no payload, increment zero_count,
            # sleep and try again
            zero_count += 1
            time.sleep(2)
        else:
            for c in vs[3:]:
                if c != '00':
                    chrs.append(chr(int(c, 16)))
            zero_count = 0
            if "BCC-> " in ''.join(chrs):
                zero_count = 4
        if (zero_count > 4):
            break
        if (total_count > 15):
            break
    return (''.join(chrs))

##############################################

def setup():
    # Copy /etc/psi/infinity/utility files to /etc/psi.conf.d then
    # restart
    global copy_info
    src_path = "/etc/psi/infinity/utility"
    dst_path = "/etc/psi.conf.d/"
    if os.path.exists(src_path):
        try:
            dirs = os.listdir(src_path)
        except OSError:
            print 'Unable to listdir: %s' % src_path
        for di in dirs:
            copy_info[di] = {
                "src" : os.path.join(src_path, di),
                "dst" : os.path.join(dst_path, di)
            }
    if not copy_info:
        print "Unable to copy over PSI conf files"
        return
    for f, info in copy_info.iteritems():
        print "Copying %s from %s to %s" % (f, info.get("src"), info.get("dst"))
        shutil.copy(info.get("src"), info.get("dst"))
    error, output = procs.get_cmd_output("/usr/bin/isi_psi_d")
    if error:
        print "Error running isi_psi_d"

def cleanup():
    # Cleanup
    for f, info in copy_info.iteritems():
        os.unlink(info.get("dst"))

def get_ext_battery_status():
    output = []
    name_w = max_width([n for n, s, e, c, cu, u, d in EXTENDED_STATUS_MAPPING])
    e, o = run_ipmiutil(0x30, 0, "C4", "09")
    if e:
        return (1, [], "Unable to get BBU Extended Status")
    for n, s, e, c, c_units, units, d in EXTENDED_STATUS_MAPPING:
        tmp = None
        val = o[s-1:e]
        val.reverse()
        if c:
            val = '0x%s' % ''.join(val)
            val = int(val, 16)
            if d and val == d:
                output.append('%*s: N/A' % (name_w, n))
            else:
                val = val * c_units
                output.append('%*s: %.2f %s' % (name_w, n, val, units))
        else:
            output.append('%*s: %s' % (name_w, n, ' '.join(val)))
    return (0, output, None)

def get_bcc_logs():
    output = []
    output.append(batt_cli("sbs -d\r\n"))
    output.append(batt_cli("log -d\r\n"))
    output.append(batt_cli("gpio -a\r\n"))
    return (0, output, None)

def dump_resume(devid):
    cmd = "/usr/bin/isi_hwtools/isi_fcb_vpd_tool --devid %s dump" % devid
    return procs.get_cmd_output(cmd)

def dump_resume_proms():
    resumes = []
    output = []
    listresume_regex = re.compile("(?P<devid>\d+)\s+(?P<chassis_type>\d+)\s+"
                                  "(?P<size>\d+)\s+(?P<primary>\w+)\s+(?P<name>.*)")
    listresume_cmd = "/usr/bin/isi_hwtools/isi_fcb_vpd_tool listresume"
    e1, o1 = procs.get_cmd_output(listresume_cmd)
    for l in o1:
        match = listresume_regex.match(l)
        if match:
            resumes.append(match.group("devid"))
    for devid in resumes:
        e2, o2 = dump_resume(devid)
        o2.append("")
        output.append(o2)
    return (0, output, None)

def get_epost_fw():
    firmware = epost.get_epost_firmware()
    comp_w = max_width([y for x, y in firmware.iteritems()])
    output = [("%*s - %s" % (comp_w, x, y)) for x, y in firmware.iteritems()]
    return (0, output, None)

def get_function(cmd):
    err_msg = None
    error, output = procs.get_cmd_output(cmd)
    if error:
        err_msg = "Error running: %s" % cmd
    return (error, output, err_msg)

def get_infinity_node_type():
    cmd = "/usr/bin/isi_hwtools/isi_epost_install -t"
    return get_function(cmd)

def get_infinity_cto_receipt():
    cmd = "/usr/bin/isi_inventory_tool --display --itemType receipt"
    return get_function(cmd)

def get_infinity_psi_receipt():
    cmd = "/usr/bin/isi_hwtools/isi_psi_tool -v"
    return get_function(cmd)

def get_infinity_drive_info():
    cmd = "/usr/bin/isi_drivenum -bmfsSz"
    return get_function(cmd)

def get_ifconfig():
    cmd = "/sbin/ifconfig"
    return get_function(cmd)

def get_pciconf():
    cmd = "/usr/sbin/pciconf -lvb"
    return get_function(cmd)

def get_hwstatus():
    cmd = "/usr/bin/isi_hwtools/isi_hw_status -gA"
    return get_function(cmd)

def get_fsr():
    cmd = "/usr/bin/isi_hwmon -f"
    return get_function(cmd)

def get_ecclog():
    cmd = "/usr/bin/isi_hwmon -e"
    return get_function(cmd)

def get_pmp():
    cmd = "/usr/bin/isi_pmp -r"
    return get_function(cmd)

def get_bbu_enable():
    cmd = "/usr/bin/isi_pmp -g"
    return get_function(cmd)

def get_camcontrol_devlist():
    cmd = "/sbin/camcontrol devlist"
    return get_function(cmd)

def get_camcontrol_smpphylist0():
    cmd = "/sbin/camcontrol smpphylist ses0"
    return get_function(cmd)

def get_camcontrol_smpphylist1():
    cmd = "/sbin/camcontrol smpphylist ses1"
    return get_function(cmd)

def get_cdes_topo():
    cmd = "/usr/bin/isi_hwtools/isi_cdesexputil -t all c0"
    return get_function(cmd)

def get_gmirror():
    cmd = "/sbin/gmirror status"
    return get_function(cmd)

def get_pmc_info():
    cmd = "/usr/bin/isi_hwtools/isi_spcvutil info"
    return get_function(cmd)

def get_pmc_devlist():
    cmd = "/usr/bin/isi_hwtools/isi_spcvutil devlist 0"
    return get_function(cmd)

def get_pmc_phystatus():
    cmd = "/usr/bin/isi_hwtools/isi_spcvutil phystatus 0"
    return get_function(cmd)

def get_sel():
    cmd = "/usr/bin/isi_hwtools/isi_ipmicmc -S -V -p l"
    return get_function(cmd)

def gpart_part_dev(device):
    cmd = "/sbin/gpart show -l %s" % device
    return get_function(cmd)

def get_gpart():
    devices = []
    output = []
    regex = re.compile("^[a]*da\d+$")
    cmd = "ls /dev"
    e, o = procs.get_cmd_output(cmd)
    for line in o:
        match = regex.match(line)
        if match:
            devices.append(match.group(0))
    for d in devices:
        e, o, err = gpart_part_dev(d)
        output.append(o)
    return (0, output, None)

def sled_ffdid(sled):
    cmd = "/usr/bin/isi_hwtools/isi_cdesexputil -d eeprom ffid -i %s" % sled
    return get_function(cmd)

def sled_capbits(sled):
    cmd = "/usr/bin/isi_hwtools/isi_cdesexputil -d eeprom capbits -i %s" % sled
    return get_function(cmd)

def get_sled_ffid():
    output = []
    for s in range(1, 6):
        output.append("Sled %s" % s)
        e, o, err = sled_ffdid(s)
        output.append(o)
        output.append("")
    return (0, output, None)

def get_sled_capbits():
    output = []
    for s in range(1, 6):
        output.append("Sled %s" % s)
        e, o, err = sled_capbits(s)
        output.append(o)
        output.append("")
    return (0, output, None)
GATHER_FUNCTIONS = [
    ("Node Type", get_infinity_node_type),
    ("EPOST Firmware", get_epost_fw),
    ("Dump Resume EEPROM", dump_resume_proms),
    ("CTO Receipt", get_infinity_cto_receipt),
    ("PSI Receipt", get_infinity_psi_receipt),
    ("Drive Info", get_infinity_drive_info),
    ("ifconfig", get_ifconfig),
    ("pciconf", get_pciconf),
    ("isi_hw_status", get_hwstatus),
    ("Fault Status Register", get_fsr),
    ("ECC Log", get_ecclog),
    ("PMP", get_pmp),
    ("BBU Enable", get_bbu_enable),
    #("BCC Logs", get_bcc_logs),
    ("Extended Battery Status", get_ext_battery_status),
    ("camcontrol devlist", get_camcontrol_devlist),
    ("camcontrol smpphylist ses0", get_camcontrol_smpphylist0),
    ("camcontrol smpphylist ses1", get_camcontrol_smpphylist1),
    ("CDES topology", get_cdes_topo),
    ("Sled FFID", get_sled_ffid),
    ("Sled capbits", get_sled_capbits),
    ("get_gmirror", get_gmirror),
    ("get_gpart", get_gpart),
    ("PMC info", get_pmc_info),
    ("PMC devlist", get_pmc_devlist),
    ("PMC phystatus", get_pmc_phystatus),
    ("SEL", get_sel),
]

def print_header_footer(test_name, start=False):
    if start:
        print "######################### Start: %s #########################" % test_name
        print ""
    else:
        print ""
        print "######################### End: %s #########################" % test_name
        print ""

def main():
    if not bootstrap.isInfinityMotherboard():
        print "This script is only supported on Infinity"
        return 0
    setup()
    print "The following gather scripts will run:"
    for name, func in GATHER_FUNCTIONS:
        print "\t- %s" % name
    print ""
    for name, func in GATHER_FUNCTIONS:
        print_header_footer(name, True)
        try:
            error, output, err_msg = func()
        except Exception as e:
            print "Error running %s: %s" % (name, str(e))
            print_header_footer(name, False)
            continue
        if error:
            print err_msg
        for line in output:
            if isinstance(line, list):
                for x in line:
                    print x
            else:
                print line
        print_header_footer(name, False)
    cleanup()
    return 0

if __name__ == "__main__":
    sys.exit(main())
