#!/bin/sh
# To build on Linux Systems without AppArmor use:
# NO_APPARMOR=1

# Library settings
PKG_CONFIG_NAME="libapparmor"
PKG_DEB_NAME="libapparmor-dev"
PKG_TEST_HEADER="<sys/apparmor.h>"
PKG_LIBS="-lapparmor"

# Linux Kernel without AppArmor
UNAME=`uname`
if [ "$NO_APPARMOR" ] || [ "$UNAME" != "Linux" ] || [ ! -d "/sys/module/apparmor" ]; then
  echo "Building without AppArmor ($UNAME)"
  sed -e "s|@cflags@||" -e "s|@libs@||" src/Makevars.in > src/Makevars
  exit 0
else
  echo "Building with AppArmor ($UNAME)"
fi

#Try pkg-config
pkg-config --exists libapparmor 2> /dev/null
if [ $? -eq 0 ]; then
  echo "Found pkg-config cflags/libs!"
  PKG_CFLAGS=$(pkg-config --cflags libapparmor)
  PKG_LIBS=$(pkg-config --libs libapparmor)
fi

# For debugging
echo "Using PKG_CFLAGS=$PKG_CFLAGS"
echo "Using PKG_LIBS=$PKG_LIBS"

# Find compiler
CPP=$(${R_HOME}/bin/R CMD config CPP)
CFLAGS=$(${R_HOME}/bin/R CMD config CFLAGS)
CPPFLAGS=$(${R_HOME}/bin/R CMD config CPPFLAGS)

# Test for header
echo "#include $PKG_TEST_HEADER" | ${CPP} ${CPPFLAGS} ${PKG_CFLAGS} ${CFLAGS} -xc - >/dev/null 2>&1

# Customize the error
if [ $? -ne 0 ]; then
  echo "On Debian/Ubuntu this package requires AppArmor."
  echo "Please run: sudo apt-get install $PKG_DEB_NAME"
  echo "To build without AppArmor support, set NO_APPARMOR=1 for example:"
  echo "install.packages('sys', configure.vars = 'NO_APPARMOR=1')"
  exit 1
fi

# Write to Makevars
sed -e "s|@cflags@|-DHAVE_APPARMOR $PKG_CFLAGS|" -e "s|@libs@|$PKG_LIBS|" src/Makevars.in > src/Makevars
exit 0
