#!/usr/bin/env bash
#
#  Simple cmake wrapper script to make it behave more like autotools
#
#  GPLv2 only - Copyright (C) 2008 - 2019
#               David Sommerseth <dazo@eurephia.org>
#
#  This program is free software; you can redistribute it and/or
#  modify it under the terms of the GNU General Public License
#  as published by the Free Software Foundation; version 2
#  of the License.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program; if not, write to the Free Software
#  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
#


# Some default variables
PREFIX="/usr/local"
BINDIR="${PREFIX}/bin"
BINDIR_SET=0
PLUGINDIR="${PREFIX}/lib/eurephia"
PLUGINDIR_SET=0
XSLTPATH="${PREFIX}/share/eurephia/xslt"
XSLTPATH_SET=0
EUREPHIADM_XSLT="${XSLTPATH}/eurephiadm"
EUREPHIADM_XSLT_SET=0
MANDIR="${PREFIX}/share/man"
MANDIR_SET=0
SQLITE3PREFIX="/var/lib/eurephia"
CMAKE_BIN="cmake"


#
#   Misc functions
#
usage() {
    cat <<EOF
configure help for eurephia

          --help               | -h        -- This help screen

   ** Main paths
          --prefix <path>                  -- Root directory of installation
                                              (default: ${PREFIX})
          --bin-dir                        -- Directory where to place binaries
                                              (default: ${BINDIR})
          --xslt-path          | -X        -- Default XSLT path
                                              (default: ${XSLTPATH})

   ** Debug options
          --debug              | -D        -- Enable verbose debug logging
          --show-secrets       | -S        -- Log passwords as clear text in log files
                               |              (only available when debug is enabled)
          --gcov               |           -- Enable gcov during building

   ** Plug-in options
          --plug-in            | -p        -- Build the eurephia plug-in for OpenVPN
          --plug-in-dir        | -P        -- Destination path for the plug-ins and other modules
                                              (default: ${PLUGINDIR})
          --openvpn-src <path> | -s <path> -- OpenVPN source directory (needed when building plug-in)
          --fw-iptables        |           -- Build iptables firewall module

   ** Database options
          --db-sqlite3         |           -- Build SQLite3 database module
          --sqlite3-path       | -sp       -- Root directory of SQLite3 eurephia database file
                                              (default: ${SQLITE3PREFIX})
   ** Administration utility options
          --eurephiadm         | -A        -- Build command line admin utility
          --eurephiadm-fw                  -- Include the firewall info even without any
                                              firewall interface being built
          --eurephiadm-xslt                -- eurephiadm XSLT root path
                                              (default: ${EUREPHIADM_XSLT})
   ** Documentation
          --doxygen                        -- Compile Doxygen developer documentation
          --man-prefix                     -- Installation prefix for man pages

   ** Build settings
          --cmake-bin                      -- CMake binary to use (default: ${CMAKE_BIN})

EOF
}

# Initialise variables which we will use later on
PARAMS=""
DB=""
FW=""
ADMIN="";
OPENVPN_SRC_DIR=""
PLUGIN=""
CONFIGUREPARAMS="$*"
CFLAGS="$CFLAGS -std=gnu99 -fno-delete-null-pointer-checks -g -Wall -Wpointer-arith -fPIC"

# Parse all arguments
while [ ! -z "$1" ]; do
      case $1 in 
          -h|--help)
              usage
              exit 0
              ;;
          --prefix)
              PREFIX="$2";
              shift
              # Apply prefix to BINDIR only if it's not been set explicitly earlier
              if [ "${BINDIR_SET}" = "0" ]; then
                  BINDIR="${PREFIX}/bin";
              fi
              # Apply prefix to PLUGINDIR only if it's not been set explicitly earlier
              if [ "${PLUGINDIR_SET}" = "0" ]; then
                  PLUGINDIR="${PREFIX}/lib/eurephia"
              fi
              # Apply prefix to XSLTPATHs only if it's not been set explicitly earlier
              if [ "${XSLTPATH_SET}" = "0" ]; then
                  XSLTPATH="${PREFIX}/share/eurephia/xslt"
                  if [ "${EUREPHIADM_XSLT_SET}" = "0" ]; then
                      EUREPHIADM_XSLT="${XSLTPATH}/eurephiadm"
                  fi
              fi
              # Apply prefix to man page directory only if not been set explicitly earlier
              if [ "${MANDIR_SET}" = "0" ]; then
                  MANDIR="${PREFIX}/share/man"
              fi
              ;;
          --bin-dir)
              BINDIR="$2"
              BINDIR_SET=1
              shift
              ;;
          -X|--xslt-path)
              XSLTPATH="$2"
              # Apply prefix to EUREPJIADM_XSLT path only if it's not been set explicitly earlier
              if [ "${EUREPHIADM_XSLT_SET}" = "0" ]; then
                  EUREPHIADM_XSLT="${XSLTPATH}/eurephiadm"
              fi
              shift
              ;;
          -D|--debug)
              PARAMS="${PARAMS} -DDEBUG=ON"
              DEBUG_WARN=1
              ;;
          -S|--show-secrets)
              PARAMS="${PARAMS} -DSHOW_SECRETS=ON"
              SECRETS_WARN=1
              ;;
          --gcov)
              CFLAGS="${CFLAGS} -fprofile-arcs -ftest-coverage"
              ;;
          -p|--plug-in)
              PARAMS="${PARAMS} -DPLUGIN=ON"
              PLUGIN="eurephia-auth"
              ;;
          -P|--plug-in-dir)
              PLUGINDIR="$2"
              PLUGINDIR_SET=1
              shift
              ;;
          -s|--openvpn-src)
              # Needs to point at at directory with the openvpn source code
              OPENVPN_SRC_DIR="$2"
              PARAMS="${PARAMS} -DOPENVPN_SRC:STRING=$2"
              shift
              ;;
          --fw-iptables)
              # Enable iptables support
              PARAMS="${PARAMS} -DFW_IPTABLES=ON"
              FW="iptables "
              ;;
          --db-sqlite3)
              # Enable the SQLite3 database driver
              PARAMS="${PARAMS} -DSQLITE3=ON"
              DB="SQLite3 "
              ;;
          --sp|--sqlite3-path)
              # Sets the install directory of the SQLite3 eurephia database file
              SQLITE3PREFIX="$2"
              shift
              ;;
          --eurephiadm|-A)
              # Enable the eurephiadm console admin utility
              PARAMS="${PARAMS} -DEUREPHIADM=ON"
              ADMIN="${ADMIN}eurephiadm "
              ;;
          --eurephiadm-fw)
              # Enable firewall features of the eurephiadm console utility
              PARAMS="${PARAMS} -DFIREWALL=ON"
              ;;
          --eurephiadm-xslt)
              # Set the path where XSLT files used by eurephiadm will be installed
              EUREPHIADM_XSLT="$2"
              EUREPHIADM_XSLT_SET=1
              shift
              ;;
          --doxygen)
              PARAMS="${PARAMS} -DDOXYGEN=ON"
              DOXY_DISTCLEAN="rm -r doxygen/eurephia-devel"
              ;;
          --man-dir)
              MANDIR="$2"
              shift
              ;;
          --cmake-bin)
              CMAKE_BIN="$2"
              shift
              ;;
          *)
              echo "Unkown option: $1"
              exit 2
              ;;
      esac
      shift
done

# Make sure we have cmake available
if [ -z "$(which ${CMAKE_BIN})" ]; then
    echo "To build eurephia, you need to install ${CMAKE_BIN} (at least version 3.x)"
    exit 1;
fi

# If we're building the openvpn plug-in, we need the openvpn source code too.
if [ ! -z "${PLUGIN}" -a -z "${OPENVPN_SRC_DIR}" ]; then
    echo "You need to give the --openvpn-src <path> option when building the eurephia plug-in"
    exit 1;
fi

# Make sure at least one database driver is enabled.
if [ -z "${DB}" ]; then
    if [ -n "${PLUGIN}" -o -n "${ADMIN}" ]; then
        echo "You need to activate at least one database driver when OpenVPN plug-in or eurephiadm is enabled"
        exit 1;
    fi
fi

# Set default parameters for the SQLite3 database
if [[ ${DB} == *SQLite3* ]]; then
    PARAMS="${PARAMS} -DSQLITE3PREFIX:STIRNG=${SQLITE3PREFIX}"
fi

# Run cmake with our parameters, and create a configure.log file at the same time
rm -f CMakeCache.txt
{
    cat <<EOF
#
# Configure run at `date`
# `uname -a`
#
# ./configure ${CONFIGUREPARAMS}

EOF
    echo -n "Using "
    ${CMAKE_BIN} --version
    ${CMAKE_BIN} . -Wno-dev ${PARAMS} -DPREFIX:STRING=${PREFIX} -DCMAKE_INSTALL_PREFIX:STRING=${PREFIX} \
        -DPLUGINDIR:STRING=${PLUGINDIR} -DBINDIR:STRING=${BINDIR} \
        -DEUREPHIADM_XSLT_PATH:STRING=${EUREPHIADM_XSLT} -DXSLTROOT:STRING=${XSLTPATH} \
        -DMANDIR:STRING=${MANDIR} -DCFLAGS:STRING="${CFLAGS}"
    export ec=$?

    # If cmake exited without failure, provide some info about the configuration
    if [ "$ec" = "0" ]; then
        echo
        echo "Building options:"
        echo "                 CFLAGS: $CFLAGS"
        echo
        echo "eurephia will be built with support for: "
        echo
        if [ -n "${DB}" ]; then
            echo "               Database: ${DB}"
        fi
        echo "               Firewall: ${FW:-"None"}"
        echo "        OpenVPN plug-in: ${PLUGIN:-"No plug-ins requested"}"
        echo "            Admin tools: ${ADMIN:-"None"}"
        echo
        echo "         Install prefix: ${PREFIX}"
        echo "           Binaries dir: ${BINDIR}"
        echo "          Man pages dir: ${MANDIR}"
        echo "           Plug-in path: ${PLUGINDIR}"
        if [ ! -z "${ADMIN}" ]; then
            echo "         XSLT base path: ${XSLTPATH}"
            echo "   eurephiadm XSLT path: ${EUREPHIADM_XSLT}"
        fi
        if [[ ${DB} == *SQLite3* ]]; then
            echo "  SQLite3 database path: ${SQLITE3PREFIX}"
        fi

        if [ "$GCOV" = "1" ]; then
            echo
            echo "  eurephia will be built with gcov.  This may have a performance impact"
        fi
        if [ -n "${DOXY_DISTCLEAN}"  ]; then
            echo
            echo "  eurephia developers documentation will be compiled under ./doxygen/eurephia-devel/"
        fi
        echo
        echo
        # Make sure user is aware of enabled debug features.
        if [ "$DEBUG_WARN" = 1 ]; then
            echo
            echo "     *******   DEBUG is enabled.  This might be a security issue   *******"
            echo
            if [ "$SECRETS_WARN" = 1 ]; then
                echo
                echo "     *******   SHOW_SECRETS is enabled.  THIS WILL LOG PASSWORDS IN CLEAR TEXT IN LOG FILES   *******"
                echo
            fi
        fi

        # Update Makefile with distclean and uninstall rules
        cat >> Makefile <<EOF
distclean : clean
	find . -type d -name "CMakeFiles" | xargs rm -rf
	find . -type f -name "cmake_install.cmake" | xargs rm -rf
	find . -type f -name CMakeCache.txt | xargs rm -rf
	find . -type f -name install_manifest.txt | xargs rm -rf
	find . -type f -name Makefile | xargs rm -rf
	find . -type f -name "*~" | xargs rm -f
	rm -f CMakeCache.txt
	${DOXY_DISTCLEAN}

uninstall :
	@echo "Uninstalling eurephia: "
	cat install_manifest.txt | xargs rm -vf
EOF
        # If SQLite3 driver is enabled, add some extra clean up rules for the uninstall rules
        if [ ! -z ${DB} ]; then
            if [ ${SQLITE3PREFIX} != ${PREFIX} ]; then
                cat >> Makefile <<EOF
	rmdir -v ${SQLITE3PREFIX}
EOF
            fi
        fi
        cat >> Makefile <<EOF
	rmdir -v ${PREFIX}
EOF

    fi
    exit $ec
} 2>&1 | tee ./configure.log
