#!/usr/bin/env python3
# patch_nrc_config.py
# Adds NULL guard for hw->conf.chandef.chan in nrc_mac_config.
# Run from: ~/nrc7292_sw_pkg/package/src/nrc/
# Usage: python3 patch_nrc_config.py

import os

src = 'nrc-mac80211.c'

if not os.path.exists(src):
    print(f'ERROR: {src} not found. Run this from ~/nrc7292_sw_pkg/package/src/nrc/')
    exit(1)

with open(src, 'r') as f:
    lines = f.readlines()

# Check if already patched — look for our specific guard comment
if any('chandef.chan is NULL during ieee80211_hw_conf_init' in l for l in lines):
    print('SKIP: already patched')
    exit(0)

# Find nrc_mac_config, then the #endif /* defined(CONFIG_SUPPORT_BD) */
# that appears within the first 30 lines of that function (before the memcpy).
insert_after = None
func_line = None

for i, line in enumerate(lines):
    if 'static int nrc_mac_config(' in line:
        func_line = i
    if func_line is not None and i > func_line and i < func_line + 30:
        if '#endif /* defined(CONFIG_SUPPORT_BD) */' in line:
            insert_after = i
            break

if insert_after is None:
    print('WARN: patch point not found — add manually before #ifdef CONFIG_SUPPORT_CHANNEL_INFO in nrc_mac_config:')
    print('      if (!hw->conf.chandef.chan)')
    print('          return 0;')
    exit(1)

guard = [
    '\t/* chandef.chan is NULL during ieee80211_hw_conf_init on first ip link set up.\n',
    '\t * The memcpy below dereferences it unconditionally -- return 0 until valid. */\n',
    '\tif (!hw->conf.chandef.chan)\n',
    '\t\treturn 0;\n',
]

lines = lines[:insert_after + 1] + guard + lines[insert_after + 1:]

with open(src, 'w') as f:
    f.writelines(lines)

print(f'OK: inserted NULL guard after line {insert_after + 1} in nrc_mac_config')
