#!/usr/bin/env python3
#
# Copyright 2021 Ettus Research, a National Instruments Brand
#
# SPDX-License-Identifier: GPL-3.0-or-later
#
"""
Helper script to generate memory init files for the ZBX CPLD.
"""

import os
import pathlib

# This is generated by running
# $ python3 /path/to/gen_zbx_cpld_regs.py zbx_cpld_regs_t.py
import zbx_cpld_regs_t

def main():
    """
    Main function
    """
    cur_dir = str(pathlib.Path(__file__).resolve().parent)

    zbx_regs = zbx_cpld_regs_t.zbx_cpld_regs_t()

    # The file dsa_control.v lists default values for documentation purposes. When
    # changing these values, make sure to also update the 'initialvalue' documentation
    # attributes in dsa_control.v
    zbx_regs.TX0_DSA1[0] = 31
    zbx_regs.TX0_DSA2[0] = 31

    zbx_regs.RX0_DSA1[0] = 15
    zbx_regs.RX0_DSA2[0] = 15
    zbx_regs.RX0_DSA3_A[0] = 15
    zbx_regs.RX0_DSA3_B[0] = 15

    # Path control defaults
    with open(os.path.join(cur_dir, "tx0_path_defaults.hex"), "w") as outfile:
        outfile.write("\n".join([
            "{:08X}".format(zbx_regs.get_reg(zbx_regs.get_addr('TX0_IF2_1_2'))),
        ] * len(zbx_regs.TX0_IF2_1_2)))
    with open(os.path.join(cur_dir, "tx1_path_defaults.hex"), "w") as outfile:
        outfile.write("\n".join([
            "{:08X}".format(zbx_regs.get_reg(zbx_regs.get_addr('TX1_IF2_1_2'))),
        ] * len(zbx_regs.TX1_IF2_1_2)))
    with open(os.path.join(cur_dir, "rx0_path_defaults.hex"), "w") as outfile:
        outfile.write("\n".join([
            "{:08X}".format(zbx_regs.get_reg(zbx_regs.get_addr('RX0_ANT_1'))),
        ] * len(zbx_regs.RX0_ANT_1)))
    with open(os.path.join(cur_dir, "rx1_path_defaults.hex"), "w") as outfile:
        outfile.write("\n".join([
            "{:08X}".format(zbx_regs.get_reg(zbx_regs.get_addr('RX1_ANT_1'))),
        ] * len(zbx_regs.RX1_ANT_1)))
    # DSA defaults
    with open(os.path.join(cur_dir, "tx_dsa_defaults.hex"), "w") as outfile:
        outfile.write("\n".join([
            "{:08X}".format(zbx_regs.get_reg(zbx_regs.get_addr('TX0_DSA1'))),
        ] * len(zbx_regs.TX0_DSA1)))
    with open(os.path.join(cur_dir, "rx_dsa_defaults.hex"), "w") as outfile:
        outfile.write("\n".join([
            "{:08X}".format(zbx_regs.get_reg(zbx_regs.get_addr('RX0_DSA1'))),
        ] * len(zbx_regs.RX0_DSA1)))

if __name__ == "__main__":
    main()
