#!/usr/bin/python

# tz_oid.py
#       --copyright--                   Copyright 2016 (C) Tranzoa, Co. All rights reserved.    Warranty: You're free and on your own here. This code is not necessarily up-to-date or of public quality.
#       --url--                         http://www.tranzoa.net/tzpython/
#       --email--                       pycode is the name to send to. tranzoa.com is the place to send to.
#       --bodstamps--
#       March 23, 2016          bar
#       --eodstamps--
##      \file
#       \namespace              tzpython.tz_oid
#
#
#       Do things with OID's.
#
#

import  os
import  re
import  sys
import  time

import  tzlib
import  url_getter

oid_cache           = {}    #: where we keep oid's we've found from the net


def find_oid_in_cache(oid) :
    """ Return a known OID and infomation about it. """
    oid = oid or ""
    if  not re.search(r'[^\.\d]', oid) :
        fn          = ""
        if  not len(oid_cache) :
            fn      = os.path.splitext(tzlib.get_ini_or_cfg_file_name('oid_cache.cfg', app_name = 'oid_cache'))[0]
            adds    = re.findall(r'(?m)^(\S+) *(.*)$', tzlib.safe_read_whole_text_file(fn) or "")
            for a in adds :
                oid_cache[a[0]] = [ a[0], a[1] or None, ]
            pass

        adds    = []
        while   oid     :
            if  oid not in oid_cache :
                rs      = url_getter.url_open_read_with_timeout("http://oid-info.com/get/%s" % oid, timeout = 4.1)
                if  rs  :
                    g   = re.search(r'<meta\s+name="Description"\s+content="OID repository[^\{]+(\{[^\r\n\}]+\})', rs or "")
                    if  g   :
                        oid_cache[oid]  = [ oid, g.group(1) ]
                        adds.append(oid_cache[oid])
                        break
                    pass
                oid_cache[oid]  = [ oid, None ]
                adds.append(oid_cache[oid])
            if  oid_cache[oid][1] != None :
                break
            oid = re.sub(r'\d+$', '', oid).rstrip('.')
        if  len(adds) :
            fn  = fn or os.path.splitext(tzlib.get_ini_or_cfg_file_name('oid_cache.cfg', app_name = 'oid_cache'))[0]
            fo  = open(fn, 'a')
            t   = time.time()
            fo.write("; %.1f %s\n" % ( t, time.asctime(time.localtime(t)), ))
            for a in adds :
                fo.write("%s %s\n" % ( a[0], re.sub(r'[^ -~]', '_', str(a[1] or "")), ))
            fo.close()
        pass

    return(oid_cache.get(oid, [ oid, None ]))


help_str    = """
%s (options) OID(s)...

Options:

Print things about the given OIDs.

"""

#
#
if __name__ == '__main__' :
    import  TZCommandLineAtFile

    program_name    = sys.argv.pop(0)

    TZCommandLineAtFile.expand_at_sign_command_line_files(sys.argv)

    while True :
        oi  = tzlib.array_find(sys.argv, [ "--help", "-h", "-?", "/?", "/h", "/H" ] )
        if  oi < 0 :    break
        del sys.argv[oi]
        print help_str % ( os.path.basename(program_name) )

        sys.exit(254)


    for oid in sys.argv :
        fnd = find_oid_in_cache(oid)
        if  not fnd[1] :
            print "Nothing found for %s!" % oid
        else :
            ps  = ""
            if  fnd[0] != oid :
                ps  = "+" + oid[len(fnd[0]):].lstrip('.')
            print "%s%s %s" % ( fnd[0], ps, fnd[1], )
        pass
    pass

#
#
#
# eof
