#! /usr/bin/python
#
# Query or control whether an LSI SAS1068 PHY is enabled.

import os
import string
import sys

import isi.app.lib.procs as procs

_MPTUTIL = "/usr/bin/isi_hwtools/isi_mptutil"

def phyGetOrSetEnable(unit, phy, enable = None):
    if enable is None:
        # Query
        flags = 0x00
        mask = 0x00
    else:
        # Set
        mask = 0x04
        if enable:
            flags = 0x00
        else:
            flags = 0x04

    cmd = "%s %d -v -cec 0x10 1 b %#x %#x %#x" % (_MPTUTIL, unit,
        0x16 + phy * 0xc, flags, mask)
    (status, output) = procs.get_cmd_output(cmd)
    if status != 0:
        raise RuntimeError, "command failed: %s" % cmd

    # Parse the output
    for i in range(len(output)):
        words = string.split(output[i])
        if len(words) == 5 and words[3] == "==>":
            newFlags = int(words[4], 0)
            break
    else:
        raise RuntimeError, "command failed: %s" % cmd

    # Return the current enable state of the PHY.
    return (newFlags & 0x04) == 0

def main(argv = None):
    if argv is None:
        argv = sys.argv
    argc = len(argv)
    if argc < 3 or argc > 4:
        print >>sys.stderr, "usage: %s unit phy [0|1]" % (
            os.path.basename(argv[0]))
        return 2
    unit = int(argv[1], 0)
    phy = int(argv[2], 0)
    if argc == 4:
        enable = int(argv[3], 0)
        phyGetOrSetEnable(unit, phy, enable)
        print "Soft reset with \"isi_mptutil %d -g host\" to make " \
            "the change take effect." % unit
    else:
        print int(phyGetOrSetEnable(unit, phy))
    return 0

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