#!/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 "Checking for 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 "Looks like AppArmor is not installed."
  echo "To install AppArmor, run: sudo apt-get install $PKG_DEB_NAME."
  if [ "$FORCE_APPARMOR" ]; then
    exit 1
  else
    echo "Disabling apparmor support"
    sed -e "s|@cflags@||" -e "s|@libs@||" src/Makevars.in > src/Makevars
    exit 0
  fi
fi

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