#!/usr/bin/env bash

if [ -z "$SAGE_LOCAL" ]; then
    echo >&2 "SAGE_LOCAL undefined ... exiting"
    echo >&2 "Maybe run 'sage -sh'?"
    exit 1
fi

# Only build iconv on Solaris, HP-UX and Cygwin. See
#     http://trac.sagemath.org/sage_trac/ticket/8567 and
#     http://trac.sagemath.org/sage_trac/ticket/9603
# for details.

case "$UNAME" in
CYGWIN|HP-UX|SunOS)
    echo "iconv will be installed as the operating system is Cygwin, HP-UX or Solaris."
    echo "These systems either lack iconv, or do not have a sufficiently capable"
    echo "version of iconv. See:"
    echo "    http://trac.sagemath.org/sage_trac/ticket/8567"
    echo "    http://trac.sagemath.org/sage_trac/ticket/9603"

    # Let an environment variable CFLAG64 specify the option to generate 64-bit
    # code. If this is not set, default to -m64:
    if [ -z "$CFLAG64" ]; then
        CFLAG64=-m64
    fi

    # If the environment variable SAGE64=yes, force building a 64-bit version:
    if [ "x$SAGE64" = xyes ]; then
        echo "Building a 64-bit version of iconv"
        # Put the flag(s) for building a 64-bit version into the C compiler
        # command rather than into CFLAGS, since (the included version of)
        # libtool would strip it off s.t. the build would otherwise fail.
        # See http://trac.sagemath.org/sage_trac/ticket/9718 for details.
        CC="$CC $CFLAG64"
        export CC
    fi

    # Disable NLS on Cygwin to be able to build libiconv without the Cygwin
    # libiconv package.
    if [ "$UNAME" = "CYGWIN" ]; then
        ICONV_CONFIGURE="--disable-nls $ICONV_CONFIGURE"
    fi

    cd src

    ./configure --prefix="$SAGE_LOCAL" --libdir="$SAGE_LOCAL/lib" $ICONV_CONFIGURE
    if [ $? -ne 0 ]; then
        echo >&2 "Error configuring iconv"
        exit 1
    fi

    $MAKE
    if [ $? -ne 0 ]; then
        echo >&2 "Error building iconv"
        exit 1
    fi

    $MAKE install
    if [ $? -ne 0 ]; then
        echo >&2 "Error installing iconv"
        exit 1
    fi
    exit 0
    ;;
*)  # Not CYGWIN, HP-UX or SunOS (Solaris)
    echo "iconv will not be installed, as we only need to build it on"
    echo "Solaris, HP-UX and Cygwin, as the system's iconv will be used"
    echo "on other platforms, rather than the one shipped with Sage."
    echo "See:"
    echo "    http://trac.sagemath.org/sage_trac/ticket/8567"
    echo "    http://trac.sagemath.org/sage_trac/ticket/9603"
    exit 0
esac

# NOT REACHED
