#!/usr/bin/env bash

if [ -z "$SAGE_ROOT" ]; then
    echo Please run the top-level bootstrap script of the Sage distribution.
    exit 1
fi

./bootstrap_m4

cd "$SAGE_ROOT"

    # Default to no filter if "-q" was not passed.
    QUIET_SED_FILTER=""
    if [ "${BOOTSTRAP_QUIET}" = "yes" ]; then
        # Otherwise, this filters the expected output from automake.
        QUIET_SED_FILTER='/configure\.ac:[0-9][0-9]*: installing /d'
    fi

    # The insanity with automake's descriptors is intended to filter
    # ONLY stderr, and to re-output the results back to stderr leaving
    # stdout alone. Basically we swap the two descriptors using a
    # third, filter, and then swap them back.
    aclocal -I m4 && \
    automake --add-missing --copy build/make/Makefile-auto 3>&1 1>&2 2>&3 \
        | sed "${QUIET_SED_FILTER}" 3>&1 1>&2 2>&3 && \
    autoconf

    st=$?
    case $st in
        0) true;; # Success

        179|16|63|127)  # no m4 for pkg-config|autotools not installed|or version too old
            if [ $DOWNLOAD = yes ]; then
                echo >&2 "Bootstrap failed, downloading required files instead."
                bootstrap_download || exit $?
            else
                if [ $st -eq 127 ]; then
                    verb="install"
                elif [ $st -eq 16 ]; then
                    verb="install pkg-config m4 macros for"
                else
                    verb="upgrade"
                fi
                echo >&2 "Bootstrap failed. Either $verb autotools; or run bootstrap with"
                echo >&2 "the -d option to download the auto-generated files instead."

                SYSTEM=$(build/bin/sage-guess-package-system)
                if test $SYSTEM != unknown; then
                    SYSTEM_PACKAGES=$(build/bin/sage-get-system-packages $SYSTEM _bootstrap)
                    if test -n "$SYSTEM_PACKAGES"; then
                        PRINT_SYS="build/bin/sage-print-system-package-command $SYSTEM --verbose=\"    \" --prompt=\"      \$ \" --sudo"
                        COMMAND=$(eval "$PRINT_SYS" update && eval "$PRINT_SYS" install $SYSTEM_PACKAGES && SAGE_ROOT="$SAGE_ROOT" eval "$PRINT_SYS" setup-build-env )
                        echo >&2
                        echo >&2 "hint: On your system ($SYSTEM), you can install the required system packages as follows:"
                        echo >&2 "$COMMAND"
                        echo >&2
                    fi
                fi
                exit $st
            fi;;

        *) exit $st;; # Failure
    esac
