#!/usr/bin/python3
# Copyright (C) 2016 Petter Reinholdtsen <pere@hungry.com>
#
# Licensed under the GNU General Public License Version 2
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.

__author__ = "Petter Reinholdtsen <pere@hungry.com>"

import re

class usbdb:
    '''Easy access to the USB vendor and product database.'''

    _dbfiles = [
        '/var/lib/usbutils/usb.ids',
        '/usr/share/misc/usb.ids',
        ]

    def __init__(self):
        self.vendors = {}
        self.products = {}
        for f in self._dbfiles:
            try:
                with open(f) as db:
                    lastvendor = None
                    for line in db.readlines():
                        if re.match(r'^#', line): continue # Skip comments
                        line = line.rstrip()
                        if re.match(r'^C ', line): break # Done parsing products
                        m = re.match(r'^([0-9a-f]{4})\s+(\S.*)$', line)
                        if m:
                            lastvendor = m.group(1)
                            self.vendors[lastvendor] = m.group(2)
                        else:
                            m = re.match(r'^\t([0-9a-f]{4})\s+(\S.*)$', line)
                            if m:
                                self.products["%s:%s" % (lastvendor, m.group(1))] \
                                    = m.group(2)
                return
            except IOError as e:
                pass

    def product(self, vendorid, productid):
        vendorname = productname = None
        if "%04x" % vendorid in self.vendors:
            vendorname = self.vendors["%04x" % vendorid]
        id = "%04x:%04x" % (vendorid, productid)
        if id in self.products:
            productname = self.products[id]
        info = {
            'vendorid'    : vendorid,
            'productid'   : productid,
            'vendorname'  : vendorname,
            'productname' : productname,
            }
        return info

def main():
    db = usbdb()
    info = db.product(0x0694, 0x0002)
    print(info)

if __name__ == '__main__':
    main()
