#!/usr/bin/bash

# This script discovers various parameters of a GAP installation,
# such as host architecture, location of the GMP library used for GAP,
# compile and link flags, etc., and writes that information to the
# file config.carat, which is then used by the Makefile.
#
#    Usage: ./configure [<path to GAP root directory>]
#           ./configure [--with-gaproot=<path to GAP root directory>]
#
# The default path to the GAP root directory is ../..

error() { printf "ERROR: %s\n" "$@" ; exit 1 ; }

# get hold of $GAPROOT
GAPROOT="$(cd ../.. && pwd)"
if [[ "$#" -ge 1 ]]; then
  option="$1" ; shift
  case "$option" in
    --with-gaproot)   GAPROOT="$1"; shift ;;
    --with-gaproot=*) GAPROOT=${option#--with-gaproot=}; ;;
    *)                GAPROOT="$option"; ;;
  esac
fi
# we need an absolute path
GAPROOT="$(cd $GAPROOT && pwd)"

# check whether $GAPROOT is valid
if [[ ! -f "$GAPROOT/sysinfo.gap" ]]; then
  error "$GAPROOT is not the root of a gap installation (no sysinfo.gap)" \
        "Please provide the absolute path of your GAP root directory as" \
        "first argument with '--with-gaproot=' to this script."
fi

# read in sysinfo
source "$GAPROOT/sysinfo.gap"

# where is the GMP library?
GMPDIR=
if [[ -d "$GAPROOT/extern/install/gmp" ]]; then
    # GAP 4.9 and later with bundled GMP
    GMPDIR="$GAPROOT/extern/install/gmp"
elif [[ -d "$GAPROOT/bin/$GAParch/extern/gmp" ]]; then
    # up to GAP 4.8 with bundled GMP
    GMPDIR="$GAPROOT/bin/$GAParch/extern/gmp"
fi

# link and include dirs for GMP library
GMPINC=
GMPLIB=
if test -n "$GMPDIR"; then
    GMPINC="-I$GMPDIR/include/"
    if [[ -f $GMPDIR/lib/libgmp.so ]]; then
        GMPLIB="-Wl,-rpath=$GMPDIR/lib/"  # shared library available
    fi
    GMPLIB="$GMPLIB -L$GMPDIR/lib/"
fi

# link and compile flag for GMP library
# we need the -m32 flag if we use GMP bundled with GAP and GAP is 32bit
GMPFLAG=
if test -n "$GMPDIR"; then
    HAVE_m32=
    if [[ -f "$GAPROOT/cnf/GAP-CFLAGS" ]]; then
        # GAP 4.9 or higher
        HAVE_m32=$(grep 'm32' "$GAPROOT/cnf/GAP-CFLAGS")
    else
        # up to GAP 4.8
        HAVE_m32=$(grep 'ABI_CFLAGS=-m32' "$GAPROOT/Makefile")
    fi
    if test -n "$HAVE_m32"; then
        GMPFLAG=-m32
    fi
fi

# C compiler GAP was built with; hack for GAP before 4.9
if test -z "$GAP_CC"; then
    eval $(grep CC= "$GAPROOT/Makefile" | head -1)
    GAP_CC=$CC
fi

# wget or curl
GET=
if test -n "$(which wget)"; then
    GET=wget
elif test -n "$(which curl)"; then
    GET=curl -O
fi  

CFLAGS="-O $GMPINC $GMPFLAG $GMPLIB"

# write out everything, so that we can include it in Makefile
echo "TOPDIR=$(pwd)/carat" > config.carat
echo "ARCHDIR=$GAParch"   >> config.carat
echo "CC=$GAP_CC"         >> config.carat
echo "CFLAGS=$CFLAGS"     >> config.carat
echo "GET=$GET"           >> config.carat
