#!/usr/bin/env python3
"""Generate idr_test_core.c from sys/libkern/linux_idr.c.

Replaces ONLY the leading #ifdef USERLAND_TEST ... #else <kernel includes>
#endif block with #include "harness_prelude.h".  Every algorithm line below
that block is kept byte-identical to the kernel source, so detected line
numbers map 1:1 onto sys/libkern/linux_idr.c.
"""
import sys

SRC = "sys/libkern/linux_idr.c"
DST = sys.argv[1]

with open(SRC) as f:
    lines = f.readlines()

start = None
els = None
endif = None
for i, l in enumerate(lines):
    if start is None and l.startswith("#ifdef USERLAND_TEST"):
        start = i
    elif start is not None and els is None and l.startswith("#else"):
        els = i
    elif els is not None and l.startswith("#endif"):
        endif = i
        break
assert start is not None and els is not None and endif is not None, \
    "could not locate USERLAND_TEST block"

out = []
out.extend(lines[:start])              # copyright comment
out.append('#include "harness_prelude.h"\n')
out.extend(lines[endif + 1:])          # algorithm, byte-identical

with open(DST, "w") as f:
    f.writelines(out)
print("wrote %s (%d lines; USERLAND_TEST block %d..%d replaced)" %
      (DST, len(out), start + 1, endif + 1))
