#!/usr/bin/env python3
"""
Patch cariboulite's smi_stream_dev.c for modern kernel APIs.

Upstream (last touched 2025-07) targets kernels older than 6.4.  Three
breakages on 6.18:

  1. vmalloc()/vfree() are no longer reachable transitively; need
     <linux/vmalloc.h> explicitly.
  2. class_create() lost its `owner` first argument in 6.4
     (torvalds/linux 1aaba11da9aa).
  3. platform_driver.remove became void-returning in 6.11
     (the remove_new transition landing back as .remove).

All edits are guarded on LINUX_VERSION_CODE so the result still builds
on pre-6.4 kernels -- which matters because DKMS will rebuild this
against whatever kernel is installed later.

Idempotent: re-running on an already-patched file is a no-op.
"""
import sys

PATH = sys.argv[1]

SHIM = """#include <linux/wait.h>

/* ---- kernel API compatibility shims (added locally, not upstream) ---- */
#include <linux/version.h>
#include <linux/vmalloc.h>      /* vmalloc/vfree: no longer included transitively */

#if LINUX_VERSION_CODE < KERNEL_VERSION(6, 4, 0)
/* class_create() dropped its owner argument in 6.4 */
#define SMI_CLASS_CREATE(name) class_create(THIS_MODULE, (name))
#else
#define SMI_CLASS_CREATE(name) class_create((name))
#endif

#if LINUX_VERSION_CODE < KERNEL_VERSION(6, 11, 0)
/* platform_driver.remove returns void from 6.11 onward */
#define SMI_REMOVE_RET  int
#define SMI_REMOVE_DONE return 0
#else
#define SMI_REMOVE_RET  void
#define SMI_REMOVE_DONE return
#endif
/* ---------------------------------------------------------------------- */
"""

EDITS = [
    # (description, old, new)
    ("compat shim block",
     "#include <linux/wait.h>\n",
     SHIM),
    ("class_create call",
     "smi_stream_class = class_create(THIS_MODULE, DEVICE_NAME);",
     "smi_stream_class = SMI_CLASS_CREATE(DEVICE_NAME);"),
    ("remove() signature",
     "static int smi_stream_dev_remove(struct platform_device *pdev)",
     "static SMI_REMOVE_RET smi_stream_dev_remove(struct platform_device *pdev)"),
    ("remove() return",
     'dev_info(inst->dev, DRIVER_NAME": smi-stream dev removed");\n    return 0;\n}',
     'dev_info(inst->dev, DRIVER_NAME": smi-stream dev removed");\n    SMI_REMOVE_DONE;\n}'),
]

src = open(PATH).read()

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

for desc, old, new in EDITS:
    n = src.count(old)
    if n != 1:
        sys.exit("FAIL: %r matched %d times (expected 1) -- aborting, "
                 "file not written" % (desc, n))
    src = src.replace(old, new)
    print("patched: %s" % desc)

open(PATH, "w").write(src)
print("wrote %s" % PATH)
