#! /usr/bin/env python
#
# Create a Linux kernel driver package for use in Runbench testing
#
# Based on an earlier script of the same name by David Russell (July 2010)
#  and patched into the converted repo history by Edward Cree (October 2017)

import os, sys, optparse, shutil

common_files = {
    'ultree': [
        'drivers/net/ethernet/sfc/util/phy_power',
        'drivers/net/ethernet/sfc/util/reset_nic',
        'drivers/net/ethernet/sfc/util/set_carrier',
        ],
    'ktree': [
        'drivers/net/ethernet/sfc/load.sh',
        'drivers/net/ethernet/sfc/load_net.sh',
        'drivers/net/ethernet/sfc/unload.sh',
        'drivers/net/ethernet/sfc/unload_net.sh',
        'drivers/net/ethernet/sfc/sfc.ko',
        'drivers/net/ethernet/sfc/sfc_driverlink.ko',
        ],
    }
if not os.uname()[2].startswith('2.6.32-573.'):
    # This is not built on RHEL 6.7
    common_files['ktree'].append('drivers/net/ethernet/sfc/sfc_ef100.ko')

ktest_files = {
    'ktree': [
        'drivers/net/ethernet/sfc/unittest_filters/arb_filter_test_mod.ko',
        'drivers/net/ethernet/sfc/unittest_filters/load_arb.sh',
        'drivers/net/ethernet/sfc/unittest_filters/unload_arb.sh',
        ],
    'ultree': [
        'drivers/net/ethernet/sfc/unittest_filters/afta',
        'drivers/net/ethernet/sfc/unittest_filters/racer',
        ],
    }

def choose_files(ktests):
    filesets = [common_files]
    if ktests:
        filesets.append(ktest_files)
    for fileset in filesets:
        for tree,files in fileset.items():
            for f in files: yield tree,f

def parse_args():
    parser = optparse.OptionParser()
    parser.add_option('-k', '--ktree', help='driver build tree path', default='.')
    parser.add_option('-u', '--ultree', help='gnu build tree path', default='.')
    parser.add_option('-U', '--ultree32', help='(64bit builds only) 32 bit '
                      'gnu build tree path')
    parser.add_option('-x', '--allow-missing', help='do not fail if this file '
                      'is missing (may be specified multiple times',
                      action='append')
    parser.add_option('-t', '--ktests', action='store_true', help=
                      'include in-kernel tests')
    parser.usage = '%prog [options] [destdir]'
    options, args = parser.parse_args()

    if args:
        options.target_dir = args[0]
    else:
        options.target_dir = 'kernel_install_package'
    return options

def main(ktree, ultree, target_dir, allow_missing=None, ultree32=None,
         ktests=False):
    if allow_missing is None:
        allow_missing = []
    for path in [ktree, ultree, ultree32]:
        if path and not os.path.isdir(path):
            print "ERROR: Cannot find",path
            sys.exit(2)

    if os.path.isdir(target_dir):
        shutil.rmtree(target_dir)

    print "TARGET=" + target_dir
        
    for tree,f in choose_files(ktests):
        if tree == 'ktree':
            trees = [(ktree,'')]
        else:
            trees = [(ultree,'')] + (ultree32 and [(ultree32,'32bit')] or [])
        for tree,subdir in trees:
            source = os.path.join(tree, f)
            destdir = os.path.join(target_dir, subdir)
            if not os.path.isfile(source):
                if os.path.basename(source) in allow_missing:
                    print "WARNING: Cannot find", source
                    continue
                else:
                    print "ERROR: Cannot find",source
                    sys.exit(3)
            print "Copy %s to $TARGET/%s" % (source, subdir)
            if not os.path.isdir(destdir):
                os.makedirs(destdir)
            if os.path.islink(source):
                dest = os.path.realpath(source)
                print "treating '%s' as a link to '%s'"%(source, dest)
                source = dest
            if os.system('cp %s %s' % (source, destdir)) != 0:
                print "ERROR: Failed to copy",source,"to",destdir
                sys.exit(4)

if __name__ == '__main__':
    options = parse_args()
    main(**options.__dict__)
