#!/bin/sh
set -e

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

# Check kernel headers present (required for libbpf 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

failed=0

check() {
    if [ $1 -eq 0 ]; then
        echo "  PASS: $2"
    else
        echo "  FAIL: $2 (exit $1)"
        failed=$((failed + 1))
    fi
}

echo "bpfcc autopkgtest — libbpf-tools smoke test"
echo "=============================================="

# 1. Key tools exist
for tool in \
    bashreadline-libbpf \
    bindsnoop-libbpf \
    biolatency-libbpf \
    biosnoop-libbpf \
    bitesize-libbpf \
    capable-libbpf \
    cpudist-libbpf \
    execsnoop-libbpf \
    filetop-libbpf \
    funclatency-libbpf \
    mountsnoop-libbpf \
    opensnoop-libbpf \
    profile-libbpf \
    runqlat-libbpf \
    tcpconnect-libbpf \
    tcplife-libbpf \
    tcptop-libbpf \
    tcpsynblibbpf \
    vfsstat-libbpf \
    vmstat-libbpf; do
    if [ -x "/usr/sbin/$tool" ]; then
        echo "  PASS: $tool exists"
    else
        echo "  SKIP: $tool not installed (may not be in this arch)"
    fi
done

# 2. --help works (exercises libbpf linking + BPF program compilation without attachment)
echo ""
echo "Functional --help checks:"

# Pick a representative set that is likely installed on all arches
for tool in bindsnoop-libbpf opensnoop-libbpf execsnoop-libbpf capable-libbpf; do
    if [ -x "/usr/sbin/$tool" ]; then
        /usr/sbin/$tool --help > /dev/null 2>&1
        rc=$?
        if [ $rc -eq 0 ] || [ $rc -eq 1 ]; then
            echo "  PASS: $tool --help (exit $rc)"
        else
            echo "  FAIL: $tool --help (exit $rc, expected 0 or 1)"
            failed=$((failed + 1))
        fi
    else
        echo "  SKIP: $tool not installed"
    fi
done

# 3. Verify libbpf shared library is present
if [ -f /usr/lib/x86_64-linux-gnu/libbpf.so ] || [ -f /usr/lib/libbpf.so ]; then
    echo "  PASS: libbpf.so found"
else
    # Search more broadly
    LIBBPF=$(find /usr/lib -name "libbpf.so*" -type f 2>/dev/null | head -1)
    if [ -n "$LIBBPF" ]; then
        echo "  PASS: libbpf.so found at $LIBBPF"
    else
        echo "  FAIL: libbpf.so not found"
        failed=$((failed + 1))
    fi
fi

echo "=============================================="
if [ $failed -gt 0 ]; then
    echo "FAILED: $failed test(s)"
    exit 1
else
    echo "ALL SMOKE TESTS PASSED"
fi

echo "libbpf-tools-smoke: PASS"
