#!/bin/sh
set -e

export AUTOPKGTEST_TMP=${AUTOPKGTEST_TMP:-/tmp/adt-python-smoke}
mkdir -p "$AUTOPKGTEST_TMP"

# Check kernel headers present (required for libbpfcc runtime)
if [ ! -f /usr/include/linux/bpf.h ]; then
    echo "FAIL: /usr/include/linux/bpf.h not found"
    echo "     Install linux-libc-dev for kernel UAPI headers"
    exit 1
fi

python3 << 'PYEOF'
import sys
import os

from bcc import BPF, disassembler
from bcc.utils import get_online_cpus, detect_language

failed = 0

def check(name, condition, msg=""):
    global failed
    if condition:
        print(f"  PASS: {name}")
    else:
        print(f"  FAIL: {name} — {msg}")
        failed += 1

print("bpfcc autopkgtest — python3-bpfcc smoke test")
print("=" * 50)

# 1. Imports
try:
    from bcc import BPF, disassembler
    from bcc.utils import get_online_cpus, detect_language
    check("imports", True)
except Exception as e:
    check("imports", False, str(e))
    sys.exit(1)

# 2. get_online_cpus
try:
    cpus = get_online_cpus()
    check("get_online_cpus", len(cpus) > 0, f"got {cpus}")
except Exception as e:
    check("get_online_cpus", False, str(e))

# 3. detect_language
try:
    lang = detect_language(["python", "ruby", "node"], os.getpid())
    check("detect_language", lang == "python", f"got {lang!r}")
except Exception as e:
    check("detect_language", False, str(e))

# 4. BPF program load (no attachment — no root needed)
try:
    text = b"""
#include <uapi/linux/ptrace.h>
int hello(void) { return 0; }
"""
    b = BPF(text=text)
    check("BPF program load", True)
except Exception as e:
    check("BPF program load", False, str(e))

# 5. disassemble_func
try:
    disasm = b.disassemble_func(b"hello")
    check("disassemble_func", "exit" in disasm, f"got: {disasm!r}")
except Exception as e:
    check("disassemble_func", False, str(e))

# 6. BPF_HASH map (skip if not root — map creation requires CAP_BPF)
if os.getuid() == 0:
    try:
        text2 = b"""
#include <uapi/linux/ptrace.h>
BPF_HASH(counter, int, int);
"""
        b2 = BPF(text=text2)
        key = 0
        counter = b2.get_table("counter")
        counter[key] = 42
        val = counter[key]
        check("BPF_HASH map", val.value == 42, f"got {val.value}")
    except Exception as e:
        check("BPF_HASH map", False, str(e))
else:
    print("  SKIP: BPF_HASH map (requires root/CAP_BPF)")

print("=" * 50)
if failed:
    print(f"FAILED: {failed} test(s)")
    sys.exit(1)
else:
    print("ALL SMOKE TESTS PASSED")
PYEOF

echo "python-smoke: PASS"
