#!/usr/bin/env python3
# Copyright (c) 2010,2019 Christian Kastner <ckk@debian.org>
#
# This script generates the firmware for zd1211- and zd1211b-based devices
# from header files from the vendor driver's original source. To generate the
# firmware, cd into the vendor driver's ./src directory and execute this file.
#
# This script is included only for informational and testing purposes only.
#
#
# 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.

import re
import struct
import os.path
import sys

headers = [
    'WS11Ub.h',
    'WS11UPh.h',
    'WS11UPhm.h',
    'WS11UPhR.h',
    'WS11Ur.h'
    ]


for header in headers:
    # WS11Ub.h -> ub, and so on
    variant = header[4:header.index('.')].lower()

    if not os.path.exists(header):
        print('File {} not found. Aborting...'.format(header), file=sys.stderr)
        sys.exit(1)

    zd1211 = open('zd1211_' + variant, 'wb')
    zd1211b = open('zd1211b_' + variant, 'wb')

    out = zd1211
    for line in open(header, 'r'):
        # The headers contain the binary data for both zd1211- and zd1211b-
        # based devices. Once we're done parsing for zd1211, simply switch
        # output to zd1211b
        if line.startswith('#elif'):
            out = zd1211b
            continue

        # Find all hex strings 0x.., convert them to ints and write them out
        # in binary
        bytes = re.findall('(?P<byte>0x[0-9A-F]{2})', line)
        for byte in bytes:
            out.write(struct.pack('B', int(byte, 16)))

    zd1211.close()
    zd1211b.close()
