#!/bin/sh
set -eu

dut=${1:?DUT path is required}
freebsd_src=${2:?FreeBSD source path is required}
output=${3:?output module path is required}
work=${4:?work directory is required}
zstdio=${5:?WITH_ZSTDIO value is required}
src=$dut/src
sys=$freebsd_src/sys
target=x86_64-unknown-freebsd15.0

case "$zstdio" in
0|1) ;;
*) printf '%s\n' 'WITH_ZSTDIO must be 0 or 1' >&2; exit 20 ;;
esac
test -d "$sys" || { printf '%s\n' "FreeBSD sys tree is absent: $sys" >&2; exit 21; }
for tool in awk clang cmp grep nm; do
	command -v "$tool" >/dev/null 2>&1 || {
		printf '%s\n' "missing B27 KLD tool: $tool" >&2
		exit 21
	}
done
test ! -e "$work" || { printf '%s\n' "B27 KLD work path exists: $work" >&2; exit 20; }
mkdir "$work"
cd "$work"
ln -s "$sys/amd64/include" machine
ln -s "$sys/x86/include" x86
ln -s "$sys/i386/include" i386
awk -f "$sys/tools/vnode_if.awk" "$sys/kern/vnode_if.src" -p
awk -f "$sys/tools/vnode_if.awk" "$sys/kern/vnode_if.src" -q
awk -f "$sys/tools/vnode_if.awk" "$sys/kern/vnode_if.src" -h
: > opt_global.h

cflags="-O2 -pipe -fno-common -fno-strict-aliasing \
-D_KERNEL -DKLD_MODULE -nostdinc -include $work/opt_global.h \
-I$work -I$sys -I$sys/contrib/ck/include -mcmodel=kernel \
-mno-red-zone -mno-mmx -mno-sse -msoft-float \
-fno-asynchronous-unwind-tables -ffreestanding -fwrapv \
-fno-omit-frame-pointer -mno-omit-leaf-frame-pointer -fstack-protector \
-Wall -Wstrict-prototypes -Wmissing-prototypes -Wpointer-arith \
-Wcast-qual -Wundef -Wno-pointer-sign -Wmissing-include-dirs \
-Wno-unknown-pragmas -Wno-address-of-packed-member \
-Wno-format-zero-length -mno-aes -mno-avx -std=gnu17 \
-D__printf__=__freebsd_kprintf__ --target=$target"

for file in super.c inode.c data.c namei.c dir.c xattr.c erofs_vnops.c \
    decompressor.c zmap.c zdata.c decompressor_lz4.c \
    decompressor_lzma.c decompressor_deflate.c decompressor_zstd.c; do
	extra=
	if test "$file" = decompressor_zstd.c; then
		extra="-I$sys/contrib/zstd/lib/freebsd"
		test "$zstdio" = 0 || extra="$extra -DZSTDIO"
	fi
	printf 'CC WITH_ZSTDIO=%s %s\n' "$zstdio" "$file"
	clang $cflags $extra -c "$src/$file" -o "${file%.c}.o"
done

clang --target="$target" -r -nostdlib ./*.o -o "$output"
nm -u "$output" | LC_ALL=C sort > B27-nm-u.txt
if ! nm -u "$output" | awk '$NF == "bcmp" { found = 1 } END { exit found }'; then
	printf '%s\n' 'B27 KLD contains an unresolved bcmp reference' >&2
	exit 1
fi
if test "$zstdio" = 0; then
	if grep -q ' ZSTD_' B27-nm-u.txt; then
		printf '%s\n' 'B27 zstdio0 KLD contains an unexpected Zstd symbol' >&2
		exit 1
	fi
else
	awk '$NF ~ /^ZSTD_/ { print $NF }' B27-nm-u.txt > B27-zstd-symbols.txt
	printf '%s\n' ZSTD_DCtx_setParameter ZSTD_createDCtx_advanced \
	    ZSTD_decompressStream ZSTD_freeDCtx ZSTD_isError > B27-zstd-expected.txt
	if ! cmp B27-zstd-expected.txt B27-zstd-symbols.txt; then
		printf '%s\n' 'B27 zstdio1 KLD Zstd ABI changed' >&2
		exit 1
	fi
fi
