#!/bin/bash -efu
# SPDX-License-Identifier: GPL-2.0-only
#
# Generate defines based on kernel having
# some symbols declared
#
# Copyright (C) 2019 <abc@openwall.com>
#

fatal() {
  echo "Error: $*" >&2
  exit 1
}

eval $(grep ^KDIR Makefile | tr -d ' ')
[ "$KDIR" ] || fatal "KDIR is not found"

WD=cc-test-build
mkdir -p $WD
cd ./$WD || fatal "cannot cd to $WD"

kbuild_test_compile() {
  local cmd

  cat > test.c
  echo obj-m = test.o > Makefile
  cmd="make -s -C $KDIR M=$PWD modules"
  echo "$cmd" > log
  if $cmd >> log 2>&1; then
    [ "$2" ] && echo "// $2 is declared ${3:+with <$3>}"
    echo "#define HAVE_$1"
    echo
  else
    echo "// ${2:-symbol} is undeclared${3:+ with <$3>}. Compile:"
    sed  "s/^/\/\/   /" test.c
    echo "// Output:"
    sed  "s/^/\/\/   /" log
    echo
    if ! grep -q undeclared log; then
      echo "Error: unexpected error from compiler" >&2
      cat log >&2
      echo >&2
      exit 3
    fi
  fi
}

kbuild_test_symbol() {
  kbuild_test_compile ${1^^} $1 ${2-} <<-EOF
	#include <linux/module.h>
	${2:+#include <$2>}
	MODULE_LICENSE("GPL");
	void *test = $1;
	EOF
}

echo "// Autogenerated for $KDIR"
echo

# helpers introduced in 613dbd95723aee7abd16860745691b6c7bda20dc
kbuild_test_symbol xt_family linux/netfilter_ipv4/ip_tables.h

echo "// End of compat_def.h"

cd $OLDPWD
rm -rf $WD

# debug output for Travis
if [ -z "${PWD/*travis*}" ]; then
  cat compat_def.h >&2
fi
