#!/usr/local/bin/python
import optparse
import re
import sys
import time

import isi.app.lib.procs as procs
import isi.hw.bootstrap as bootstrap

opts = None
IPMICMC = "/usr/bin/isi_hwtools/isi_ipmicmc"

# 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 debug_print(s):
    """Prints a string while in debug mode"""
    if opts.debug:
        print s

def getipmi(cmd):
    """Executes a command and returns the space-delimited output as a list"""
    debug_print("getipmi: %s" % cmd)
    error, output = procs.get_cmd_output(cmd)
    if error:
        raise Exception("Error running %s: cmd - %s" % (IPMICMC, cmd))
    data_regex = re.compile("([0-9a-fA-F]{2}\s+)+")
    data = filter(lambda l: data_regex.match(l), output)
    debug_print("gotipmi: %s" % data)
    data = ' '.join(data)
    data = data.strip()
    vs = data.split(" ")
    vs = vs[2:]
    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
        debug_print("wr_bytes %s" % wr_bytes)
    else:
        add_cksum = False

    ipmitool_raw = "%s -V -a bmc -R " % IPMICMC
    cp_bmc = " %02x%02x" % (BMC_NETFN, BMC_CMD)
    cp_bbu = ("%02x%02x%02x" % (BBU_FRU, BBU_DEV, BBU_IDX))
    # PMBus pointer is not used
    pmb_ptr = 0xff

    # 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("%02x" % b)
    wr_str = ''.join(b_ch)

    cp_cmd = ("%02x%02x%02x%02x%s" %
        ( page, pmb_ptr, bytes_rd, command, wr_str ))

    cmd = ipmitool_raw + 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))
    debug_print(cmd_list)

    # 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, 0xbf, [])
        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
        # 0xbf bytes from Page 0x7 Command 0x75
        vs = getipmi_bridged(0x07, 0x75, 0xbf, [])
        debug_print(vs)
        # 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[4:-1]:
                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 getargs(args):
    global opts
    argparser = optparse.OptionParser()
    argparser.add_option(
        '-d', '--debug',
        action="store_true",
        help="Include debug prints")
    (opts, _) = argparser.parse_args(args)
    return opts

def main(args):
    global DEBUG
    if not bootstrap.isInfinityMotherboard():
        print "%s is not supported on this platform" % __name__
        return 0

    try:
        sbs_output = batt_cli("sbs -d\r\n")
        log_output = batt_cli("log -d\r\n")
        gpio_output = batt_cli("gpio -a\r\n")
        batt_output = batt_cli("batt -d\r\n")
    except Exception, e:
        print e
        return 1
    print sbs_output
    print log_output
    print gpio_output
    print batt_output
    return 0

if __name__ == "__main__":
    sys.exit(main(getargs(sys.argv[1:])))
