#!/bin/sh
set -e

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

failed=0

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

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

# 1. Check for bpfcc tools in /usr/sbin
tools_found=0
for tool in /usr/sbin/*-bpfcc; do
    if [ -x "$tool" ]; then
        tools_found=$((tools_found + 1))
    fi
done

if [ $tools_found -gt 0 ]; then
    echo "  PASS: found $tools_found bpfcc tools in /usr/sbin"
else
    echo "  SKIP: no bpfcc tools found in /usr/sbin (may be installed elsewhere)"
fi

# 2. --help checks for representative tools
# Use a small representative set to keep test fast
for tool in bindsnoop-bpfcc opensnoop-bpfcc execsnoop-bpfcc capable-bpfcc; do
    path="/usr/sbin/$tool"
    if [ -x "$path" ]; then
        # --help should exit 0 or 1 (some tools exit 1 for help)
        "$path" --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. Check tools directory
if [ -d /usr/share/bcc/tools ]; then
    # Check for at least one tool script
    if find /usr/share/bcc/tools -type f 2>/dev/null | head -1 | grep -q .; then
        echo "  PASS: /usr/share/bcc/tools directory exists with files"
    else
        echo "  SKIP: /usr/share/bcc/tools empty"
    fi
else
    echo "  SKIP: /usr/share/bcc/tools not found"
fi

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

echo "bpfcc-tools-smoke: PASS"
