#!/usr/bin/env bash

########################################################################
# Regenerate auto-generated files (e.g. configure)
#
# If the -s option is given, save the autogenerated scripts in
# $SAGE_ROOT/upstream/configure-$CONFVERSION.tar.gz where CONFVERSION
# is the version number stored in
# build/pkgs/configure/package-version.txt
#
# If optional argument -i is given, then automatically increment the
# version number.
#
# If optional argument -d is given and bootstrapping failed, instead
# extract the files from a local configure tarball, downloading it if
# needed. If -D is given, don't try to bootstrap and always extract or
# download.
########################################################################

# Either run this script from SAGE_ROOT or make sure that SAGE_ROOT
# is set
test -z "$SAGE_ROOT" || cd "$SAGE_ROOT"

PKG=build/pkgs/configure
MAKE="${MAKE:-make}"
CONFVERSION=`cat $PKG/package-version.txt`


bootstrap () {
    aclocal -I m4 && \
    automake --add-missing --copy build/make/Makefile-auto && \
    autoconf

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

        63|127)  # 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"
                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."
                exit $st
            fi;;

        *) exit $st;; # Failure
    esac
}

# Bootstrap by downloading the auto-generated files
bootstrap-download () {
    build/bin/sage-download-file configure-$CONFVERSION.tar.gz
    if [ $? -ne 0 ]; then
        echo >&2 "Error: downloading configure-$CONFVERSION.tar.gz failed"
        exit 1
    fi

    # The "m" option to tar ensures that timestamps are set to the
    # current time, not taken from the tarball.
    # We need these files to be more recent than the input files
    # like configure.ac, otherwise "make" gets confused.
    tar xzmf $CONFBALL || exit $?
}

save () {
    set -e

    # Check that config.guess is sufficiently recent
    if ! grep '^timestamp=.*201[5-9]' config/config.guess >/dev/null; then
        echo >&2 "Error: config.guess is outdated:"
        grep >&2 '^timestamp=' config/config.guess
        echo >&2 "You should update the 'gnuconfig' or 'automake' package and try again"
        exit 63
    fi

    # Create configure tarball
    echo "Creating $CONFBALL..."
    mkdir -p upstream
    tar zcf "$CONFBALL" configure config/* build/make/Makefile-auto.in
    
    # Update version number
    echo "$CONFVERSION" >$PKG/package-version.txt
    
    # Compute checksum
    SAGE_ROOT=. src/bin/sage-fix-pkg-checksums "$CONFBALL"
}


usage () {
    echo >&2 "Usage: $0 [-d|-D|-s] [-i] [-h]"
}


# Parse options
SAVE=no
DOWNLOAD=no
ALWAYSDOWNLOAD=no
while getopts "Ddsih" OPTION
do
     case "$OPTION" in
         D) ALWAYSDOWNLOAD=yes; DOWNLOAD=yes;;
         d) DOWNLOAD=yes;;
         s) SAVE=yes;;
         i) CONFVERSION=$(( CONFVERSION + 1 ));;
         h) usage; exit 0;;
         ?) usage; exit 2;;
     esac
done
CONFBALL="upstream/configure-$CONFVERSION.tar.gz"

if [ $DOWNLOAD$SAVE = yesyes ]; then
    echo >&2 "$0: refusing to download and save."
    usage
    exit 2
fi

# Start cleanly (it's not a problem if this fails)
$MAKE bootstrap-clean 2>/dev/null
mkdir config 2>/dev/null

# Get autotools from our own package into PATH (Trac #21214).
# If Sage has not been built yet, this will fail due to a missing
# sage-env-config. We just ignore that error.
source src/bin/sage-env 2>/dev/null


if [ $ALWAYSDOWNLOAD = yes ]; then
    bootstrap-download || exit $?
else
    bootstrap
fi

if [ $SAVE = yes ]; then
    save
fi
