#!@PYTHON@
"""massagevendor - convert IEEE oui.csv to ethercodes.dat format"""
# @(#) $Id: massagevendor.py.in 1535 2023-09-05 16:44:51Z leres $ (LBL)
#
#  Copyright (c) 2000, 2004, 2009, 2010, 2013, 2015, 2016, 2019
#  The Regents of the University of California. All rights reserved.
#
#  Redistribution and use in source and binary forms, with or without
#  modification, are permitted provided that the following conditions are met:
#      * Redistributions of source code must retain the above copyright
#        notice, this list of conditions and the following disclaimer.
#      * Redistributions in binary form must reproduce the above copyright
#        notice, this list of conditions and the following disclaimer in the
#        documentation and/or other materials provided with the distribution.
#      * Neither the name of the University nor the names of its contributors
#        may be used to endorse or promote products derived from this software
#        without specific prior written permission.
#
#  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
#  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
#  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
#  ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
#  FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
#  DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
#  OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
#  HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
#  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
#  OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
#  SUCH DAMAGE.
#
# Massage:
#
#       https://standards-oui.ieee.org/oui/oui.csv
#
#  into ethercodes.dat format.
#

from __future__ import print_function

import argparse
import csv
import os
import sys

OPTS = None
PROG = '?'

DEFAULT_ZEROPAD = bool(@ZEROPAD@)

def process(f):
    """Massage one csv file"""
    reader = csv.reader(f, delimiter=',', quotechar='"')
    lines = []
    for row in reader:
        if len(row) < 3:
            continue
        if row[0] != 'MA-L':
            continue

        vendor = row[1].lower()
        if len(vendor) != 6:
            continue
        tup = [vendor[i:i + 2] for i in range(0, 6, 2)]
        if not OPTS.zeropad:
            tup = [x[1:] if  x[0] == '0' else x for x in tup]
        vendor = ':'.join(tup)

        company = row[2]
        if sys.version_info[0] < 3:
            company = unicode(company, 'utf-8')
        company = company.encode('utf-8').decode('ascii', 'ignore')

        lines.append('%s\t%s' % (vendor, company))

    lines.sort()
    for line in lines:
        print('%s' % line)

def main(argv=None):
    """Parse options and execute"""
    global OPTS
    global PROG

    if not argv:
        argv = sys.argv

#    # Make sure /usr/local/sbin is on our path
#    pathstr = 'PATH'
#    localsbin = '/usr/local/sbin'
#    if pathstr not in os.environ:
#        os.environ[pathstr] = localsbin
#    elif localsbin not in os.environ[pathstr]:
#        os.environ[pathstr] = '%s:%s' % (localsbin, os.environ[pathstr])

    PROG = os.path.basename(argv[0])
    version = '$Revision: 1535 $'.strip('$').rstrip()

    parser = argparse.ArgumentParser(
        formatter_class=argparse.RawTextHelpFormatter)
    parser.add_argument('--version', action='version', version=version)
    parser.add_argument('-d', dest='debug', action='count', default=0,
        help='turn on debugging')
    parser.add_argument('-v', dest='verbose', action='count', default=0,
        help='verbose messages')

    if DEFAULT_ZEROPAD:
        extra_z = ' (default)'
        extra_n = ''
    else:
        extra_z = ''
        extra_n = ' (default)'
    parser.add_argument('-Z', dest='zeropad', action='store_true',
        default=DEFAULT_ZEROPAD,
        help='zero fill ethernet addresses%s' % extra_z)
    parser.add_argument('-C', dest='zeropad', action='store_false',
        help='compact ethernet addresses%s' % extra_n)

    parser.add_argument('--debugger', action='store_true',
        help=argparse.SUPPRESS)

    parser.add_argument('csv', metavar='CSV', nargs='?',
        help='csv iput file')

    OPTS = parser.parse_args()

    # argparse debugging
    if OPTS.debug > 1:
        for key in dir(OPTS):
            if not key.startswith('_'):
                print('# %s=%s' % (key, getattr(OPTS, key)), file=sys.stderr)

    # Interactive debugging
    if OPTS.debugger:
        import pdb
        pdb.set_trace()

    if not OPTS.csv:
        try:
            process(sys.stdin)
        except KeyboardInterrupt:
            return 1
        return 0

    try:
        with open(OPTS.csv) as f:
            process(f)
    except (IOError, OSError) as e:
        print('%s: %s: %s' % (PROG, OPTS.csv, e.strerror), file=sys.stderr)
        return 1
    except KeyboardInterrupt:
        return 1
    return 0

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