# This is a function to find the name of the installed library
# for some device given by idVendor and idProduct.
# It has some special environment properties hardcoded and is
# only a feasibility study. It would need some work for a real product.

from __future__ import print_function
import os,sys,string

# call this only on Windows and only for libusb0 served devices

try:
    from _winreg import *
except:
    from winreg import *

#@staticmethod
def find_installed_library(vid,pid):
    print("find installed library for 0x%04x 0x%04x" % (vid,pid))

#   registry is back, I knew it was inside it

    vidpid = r"\VID_%04x&PID_%04x" % (vid,pid)

    regpath = r"SYSTEM\CurrentControlSet\ENUM\USB" + vidpid
    try: 
       key = OpenKey(HKEY_LOCAL_MACHINE,regpath,0,KEY_READ) 
    except Exception as message:
       print ("key",message)
       return None
    try:
        enumkey = EnumKey(key,0)
    except Exception as message:
        pass ; print("enumkey",message)
        return None
#   now let us find the inf file name    
    newkey = OpenKeyEx(key,enumkey,0,KEY_READ)
    service,Size = QueryValueEx(newkey,"Service")
    print("Service",service)
    deviceDesc,Size = QueryValueEx(newkey,"DeviceDesc")
    print("deviceDesc",deviceDesc)
    ix = string.index(deviceDesc,";")
    deviceName = deviceDesc[ix+1:].lower()
    print("deviceName",deviceName)
    f = ""
# now let us go shopping to the DriverStore
    dirname = r"C:\Windows\system32\DriverStore\Filerepository"
    for entry in os.listdir(dirname):
         if entry.lower().startswith(deviceName):
              print("entry",entry)
              creation_date = 0; lib=""; F = ""
# now let us traverse the subtree to find a library
              for root,dirs,files in os.walk(dirname+"\\"+entry):
                  for f in files:
                      if f.endswith(".dll") and not root.endswith("x86") : 
                          print("root",root,"file",f)
                          try:
                             created = os.stat(root + "\\" + f)[9]
                             print(created)
                             if created > creation_date :
                                creation_date = created
                                lib = root + "\\" + f
                                F = f
                          except Exception as message:
                             print(message)
     
                          
    return F[0:-4]
    print("no file found for",deviceName)
    return None

if __name__ == "__main__":
    try:
       vid = int(sys.argv[1],16); pid = int(sys.argv[2],16)
    except Exception as message:
       #print (message)
       vid = 0x5656;  pid = 0x0834  
    f = find_installed_library(vid,pid)
    print ("library is ",f)