#!/bin/bash

set -e

ME=$(dirname $0)
SRC_NFT="$(dirname $0)/../../tools/nft-afl"

cd $ME/../..

echo "# nft tokens and common strings, autogenerated via $0" >  tests/afl++/nft.dict
grep %token src/parser_bison.y | while read token comment value; do
	echo $value
done | grep -v "[A-Z]" | sort | cut -f 1 -d " " |  grep '^"' >> tests/afl++/nft.dict

cat >> tests/afl++/nft.dict <<EOF
"\"quoted\""
"{"
"}"
"["
"]"
";"
":"
","
"."
"192.168.0.1"
"65535"
";;"
"\x09"
"\x0d\x0a"
"\x0a"
EOF

for d in "tests/afl++/in/" "tests/afl++/in-json" "tests/afl++/out/";do
	test -d "$d" || mkdir "$d"
done

find tests/shell/testcases -type f -name '*.nft' | while read filename; do
	install -m 644 $filename "tests/afl++/in/"$(echo $filename | tr / _)
done
find tests/shell/testcases -type f -name '*.json-nft' | while read filename; do
	install -m 644 $filename "tests/afl++/in-json/"$(echo $filename | tr / _)
done

echo "built initial set of inputs to fuzz from shell test case dump files."
echo "sample invocations:"
echo "unshare -n afl-fuzz -g 16 -G 2000 -t 5000 -i tests/afl++/in -o tests/afl++/out -- "$SRC_NFT" --fuzzer netlink-ro"
echo "unshare -n afl-fuzz -g 16 -G 2000 -t 5000 -i tests/afl++/in-json -o tests/afl++/out -- "$SRC_NFT" -j --check --fuzzer netlink-rw"
