#!/bin/sh
set -eu

if [ "$#" -ne 1 ]; then
    printf '%s\n' "usage: audit-static-base.sh ROOTFS" >&2
    exit 2
fi

rootfs=$1
failed=0
count=0

while IFS= read -r executable; do
    description=$(file "$executable")
    case "$description" in
        *ELF*)
            count=$((count + 1))
            if objdump -p "$executable" |
                grep -Eq '^[[:space:]]*(INTERP|NEEDED)[[:space:]]'; then
                printf '%s\n' "dynamic base executable: $executable" >&2
                failed=1
            fi
            ;;
    esac
done <<EOF
$(find "$rootfs" -type f -perm -0100 -print | LC_ALL=C sort)
EOF

if [ "$count" -eq 0 ]; then
    printf '%s\n' "no ELF executables found under $rootfs" >&2
    exit 1
fi

if [ "$failed" -ne 0 ]; then
    exit 1
fi

printf '%s\n' "static ELF audit passed: $count executables"
