#!/usr/bin/env python3
"""Make tx_test's -g argument actually set the transmit power.

tx_test parses -g into state.gain, validates it, prints it -- and then
calls cariboulite_radio_set_tx_power(radio, 0) with a hardcoded zero, so
the setting never reaches the hardware and the radiated level does not
move across the whole 0..69 range.

This is a userspace bug, not an FPGA one. The digital sample amplitude is
already carried correctly by the fixed datapath; only the RF gain stage
is being ignored.

The mapping follows the SoapySDR plugin's own convention, tx_power_dbm =
gain - 18, so a given -g means the same thing in both. set_tx_power then
clamps to the channel's real range (-14..+14 dBm for S1G, -12..+14 for
HiF), which is about 26-28 dB of usable control, not 69.

Idempotent.

  patch_tx_gain.py <path-to>/software/tx_test/tx_test.c
"""
import sys

PATH = sys.argv[1]

OLD = "    cariboulite_radio_set_tx_power(state.radio, 0);"
NEW = ("    // was: set_tx_power(state.radio, 0) -- -g was parsed and then\n"
       "    // thrown away. Same gain->dBm convention as the Soapy plugin.\n"
       "    if (state.gain >= 0)\n"
       "        cariboulite_radio_set_tx_power(state.radio, (int)(state.gain) - 18);\n"
       "    else\n"
       "        cariboulite_radio_set_tx_power(state.radio, 0);")

src = open(PATH).read()

if "thrown away" in src:
    print("already patched, nothing to do")
    sys.exit(0)

n = src.count(OLD)
if n != 1:
    sys.exit("FAIL: anchor matched %d times (expected 1) -- not writing" % n)

open(PATH, "w").write(src.replace(OLD, NEW))
print("patched: tx_test.c now applies -g as tx power (gain - 18 dBm)")
