#!/bin/bash
# scmp-info.sh - Comprehensive analysis of seccomp BPF files
# Usage: ./scmp-info.sh <bpf-file>
#
# Copyright (c) 2025 Ali Polatel <alip@chesswob.org>
# SPDX-License-Identifier: GPL-3.0

set -e

# Function to print colored headers.
print_header() {
    printf -- "=== %s ===\n" "$1"
}

print_section() {
    printf -- "--- %s ---\n" "$1"
}

print_error() {
    printf -- "Error: %s\n" "$1" >&2
}

print_success() {
    printf -- "%s\n" "$1"
}

# Check if seccomp-tools is available.
check_seccomp_tools() {
    if ! command -v seccomp-tools >/dev/null 2>&1; then
        print_error "seccomp-tools not found. Please install it:"
        printf "  gem install seccomp-tools\n"
        exit 1
    fi
}

# Validate input arguments.
validate_input() {
    if [ $# -ne 1 ]; then
        print_error "Usage: $0 <bpf-file>"
        exit 1
    fi

    BPF_FILE="$1"

    if [ ! -f "$BPF_FILE" ]; then
        print_error "File '$BPF_FILE' not found!"
        exit 1
    fi

    if [ ! -r "$BPF_FILE" ]; then
        print_error "File '$BPF_FILE' is not readable!"
        exit 1
    fi
}

# Get basic file information
get_file_info() {
    print_section "File Information"

    # File size and instruction count (8 bytes per instruction).
    file_size=$(wc -c < "$BPF_FILE")
    instruction_count=$((file_size / 8))

    printf "File: %s\n" "$BPF_FILE"
    printf "Size: %d bytes\n" "$file_size"
    printf "Instructions: %d\n" "$instruction_count"
}

# Disassemble BPF filter to human-readable format.
disassemble_filter() {
    print_section "Disassembled Filter"
    seccomp-tools disasm "$BPF_FILE"
}

# Main execution.
main() {
    check_seccomp_tools
    validate_input "$@"

    print_header "Seccomp BPF Analysis: $(basename "$BPF_FILE" .bpf)"

    get_file_info
    echo

    disassemble_filter
}

# Execute main function with all arguments.
main "$@"
