#!/usr/bin/python3
# vim:expandtab:autoindent:tabstop=4:shiftwidth=4:filetype=python:tw=0

  #############################################################################
  #
  # Copyright (c) 2005 Dell Computer Corporation
  # Dual Licenced under GNU GPL and OSL
  #
  #############################################################################
"""smbios-sys-info"""



# import arranged alphabetically
import gettext
import locale
import os
import sys

# the following vars are all substituted on install
# this bin isnt byte-compiled, so this is ok
pythondir="/usr/lib/python3.10/site-packages"
clidir="/usr/share/smbios-utils"
# end vars

# import all local modules after this.
sys.path.insert(0,pythondir)
sys.path.insert(0,clidir)

import cli
from libsmbios_c import system_info as sysinfo, smbios, localedir, GETTEXT_PACKAGE
from libsmbios_c.trace_decorator import traceLog, getLog

__VERSION__="2.4.3"

locale.setlocale(locale.LC_ALL, '')
gettext.install(GETTEXT_PACKAGE, localedir)

moduleLog = getLog()
verboseLog = getLog(prefix="verbose.")

def notSettable(*args):
    raise ValueError

def getEsc():
    try:
        return int(sysinfo.get_service_tag(), 36)
    except (ValueError,) as e:
        return 0

def get_system_id():
    return "0x%04X" % sysinfo.get_dell_system_id()

info_list = {
        "library-version": ( _("Libsmbios version"), sysinfo.get_library_version_string, notSettable),
        "product-name": ( _("Product Name"), sysinfo.get_system_name, notSettable ),
        "product-vendor": ( _("Vendor"), sysinfo.get_vendor_name, notSettable),
        "bios-version": ( _("BIOS Version"), sysinfo.get_bios_version, notSettable),
        "product-id": ( _("System ID"), get_system_id, notSettable),
        "service-tag": ( _("Service Tag"), sysinfo.get_service_tag, sysinfo.set_service_tag),
        "express-service-code": ( _("Express Service Code"), getEsc, notSettable),
        "asset-tag": ( _("Asset Tag"), sysinfo.get_asset_tag, sysinfo.set_asset_tag ),
        "property-tag": ( _("Property Ownership Tag"), sysinfo.get_property_ownership_tag, sysinfo.set_property_ownership_tag),
    }

output_order = [ "library-version", "product-name", "product-vendor", "bios-version", "product-id", "service-tag", "express-service-code", "asset-tag", "property-tag"]

for tag in list(info_list.keys()):
    if tag not in output_order:
        raise IndexError

def command_parse():
    parser = cli.OptionParser(usage=__doc__, version=__VERSION__)

    parser.add_option('--service-tag', action="store_const", dest="taglist", const=["service-tag"], default=list(info_list.keys()), help= _("Show or set service tag"), )
    parser.add_option('--asset-tag', action="store_const", dest="taglist", const=["asset-tag"], help= _("Show or set asset tag"), )
    parser.add_option('--property-tag', action="store_const", dest="taglist", const=["property-tag"], help= _("Show or set property tag"), )
    parser.add_option('--set', action="store", dest="set", default=None, help= _("Set specified tag to new value"), )

    cli.addStdOptions(parser)
    return parser.parse_args()

def main():
    exit_code = 0
    (options, args) = command_parse()
    cli.setup_std_options(options)

    try:
        #instantiate smbios table to ensure we have good perms, etc
        s = smbios.SmbiosTable()

        if options.set and len(options.taglist) > 1:
            print(_("Specify which tag to set."))
            raise IndexError
        elif options.set:
            print(_("Current tag value:"))

        maxlen=0
        for t in options.taglist:
            slen = len(info_list[t][0]) + 1
            if slen>maxlen: maxlen=slen

        for info in [ info_list[t] for t in output_order if t in options.taglist ]:
            label = info[0]
            sys.stdout.write( "%s:" % label)
            sys.stdout.write( " " * (maxlen-len(label)))
            try:
                output = info[1]()
#                if type(output) == bytes:
 #                   output = output.decode('utf-8')
                sys.stdout.write( "%s\n" % output )
            except Exception as e:
                sys.stdout.write( "%s\n" % e )


        if options.set:
            print()
            print(_("Setting new tag value: %s") % options.set)
            fn = info_list[ options.taglist[0] ][2]
            exit_code = fn(options.set.encode(), options.password_ascii, options.password_scancode)

    except (smbios.TableParseError,) as e:
        exit_code=3
        moduleLog.info( _("ERROR: Could not parse system SMBIOS table.") )
        verboseLog.info( _("The smbios library returned this error:") )
        verboseLog.info( str(e) )
        moduleLog.info( cli.standardFailMessage )

    return exit_code

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

