#!/usr/bin/env python

"""
XXX Convert this script to use PSI-backed settings or eliminate
XXX it in favor of using the usysctl ui or something like that
"""

import os
import sys

import isi.hw.ipmi as ipmi

USAGE_TEXT = """
Usage:
%s setting [value]

Settings:
    enabled         Enable or disable cache reads and writes. Valid values are
                    True and False.
    expire_enabled  Enable or disable expiration of the cache -- This is used
                    by hwmon to force all non-critical processes to only read
                    from the cache when hardware is unresponsive. Valid values
                    are True and False.
    expire          Expiration period of the cache. Valid values are integers
                    greater than zero.
    refresh         Expiration period of the cache settings -- This controls
                    how often the settings are refreshed by processes that are
                    using the cache. This setting should be less than the hwmon
                    quiescesleep setting. Valid values are integers greater
                    than zero.
""" % os.path.basename(__file__)

def usage(err_str):
    print err_str
    print USAGE_TEXT
    exit(1)

def main():
    if len(sys.argv) < 2 or len(sys.argv) > 3:
        usage("Invalid argument(s)")
    setting = sys.argv[1]
    value = None
    if len(sys.argv) == 3:
        value = sys.argv[2]
        if value.lower() == "true":
            value = True
        elif value.lower() == "false":
            value = False
        else:
            try:
                value = int(value)
            except ValueError:
                usage("Invalid setting value")

    settings = ipmi.getCacheSettings()
    if setting not in settings:
        usage("Invalid setting name")
    if value is not None:
        if type(value) != type(settings[setting]):
            usage("Type of value does not match setting")
        if type(value) == int and value < 0:
            usage("Negative values are not allowed")
        settings[setting] = value
        ipmi.saveCacheSettings(settings)
    else:
        print "%s: %s" % (setting, settings[setting])

if __name__ == '__main__':
    main()
