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

import os
import string
import sys
import time

import isi.app.lib.procs as procs

_MPSUTIL = "/usr/bin/isi_hwtools/isi_mpsutil"

def phyGetOrSetEnable(phy, enable = None):
    if enable is None:
        # Query
        opt = '-t %d' % phy
    else:
        # Set
        if enable:
            opt = '-PE %d' % phy
        else:
            opt = '-PD %d' % phy

    cmd = "%s %s" % (_MPSUTIL, opt) 
    (status, output) = procs.get_cmd_output(cmd)
    if status != 0:
        raise RuntimeError, "command failed: %s" % cmd

    # Parse the output (the first four lines are header
    linen = 0
    for line in output:
        if linen > 3:
            words = line.split()
            if int(words[0]) == phy:
                if words[1] in [ '1.5', '3.0', '6.0' ]:
                    return 1
                else:
                    return 0
        linen = linen + 1

    # Return the current enable state of the PHY.
    return 0

def usage(argv):
    print >>sys.stderr, "usage: %s <phynum> [ 0(disable) | 1(enable) ]" % (
        os.path.basename(argv[0]))
    sys.exit(2)

def main(argv = None):
    if argv is None:
        argv = sys.argv
    argc = len(argv)
    if argc < 2 or argc > 3:
        usage(argv);
    enable = None
    try:
        phy = int(argv[1], 0)
        if argc == 3:
            enable = int(argv[2], 0)
    except ValueError:
        usage(argv)
    if enable is not None:
        phyGetOrSetEnable(phy, enable)
        time.sleep(1)
        print int(phyGetOrSetEnable(phy))
    else:
        print int(phyGetOrSetEnable(phy))
    return 0

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