#!/usr/bin/env bash

########################################################
# Update the Sage version
# To be called by the release manager
########################################################

CMD="${0##*/}"

die () {
    echo >&2 -e "$@"
    exit 1
}

usage () {
    echo "usage: $CMD <SAGE_VERSION>"
}

if [ $# -ne 1 ]; then
    usage
    die
fi

if [ -z "$SAGE_ROOT" ]; then
    die "must be run from within a Sage enviroment, or with SAGE_ROOT provided"
fi

if [ -z "$SAGE_SRC" ]; then
    die "must be run from within a Sage enviroment, or with SAGE_SRC provided"
fi

set -e

# If $1 starts with "sage-", remove this prefix
SAGE_VERSION=`echo "$1" | sed 's/^sage-//'`
SAGE_RELEASE_DATE=`date -u +'%Y-%m-%d'`
SAGE_VERSION_BANNER="SageMath version $SAGE_VERSION, Release Date: $SAGE_RELEASE_DATE"

# Update Sage version file for Python in SAGE_SRC/sage
cat <<EOF > "$SAGE_SRC/sage/version.py"
# Sage version information for Python scripts
# This file is auto-generated by the sage-update-version script, do not edit!
version = '$SAGE_VERSION'
date = '$SAGE_RELEASE_DATE'
banner = '$SAGE_VERSION_BANNER'
EOF

# Update Sage version file for shell scripts in SAGE_SRC/bin/sage-version.sh
cat <<EOF > "$SAGE_SRC/bin/sage-version.sh"
# Sage version information for shell scripts
# This file is auto-generated by the sage-update-version script, do not edit!
SAGE_VERSION='$SAGE_VERSION'
SAGE_RELEASE_DATE='$SAGE_RELEASE_DATE'
SAGE_VERSION_BANNER='$SAGE_VERSION_BANNER'
EOF

# Create a top-level VERSION.txt file, which some external utilities rely on
echo "$SAGE_VERSION_BANNER" > "$SAGE_ROOT/VERSION.txt"

# Regenerate auto-generated files tarball
"$SAGE_ROOT/bootstrap" -i -s

# Commit auto-generated changes
git commit -m "Updated SageMath version to $SAGE_VERSION" -- \
    "$SAGE_ROOT/VERSION.txt" \
    "$SAGE_SRC/sage/version.py" \
    "$SAGE_SRC/bin/sage-version.sh" \
    "$SAGE_ROOT/build/pkgs/configure/checksums.ini" \
    "$SAGE_ROOT/build/pkgs/configure/package-version.txt" \
    || die "Error committing to the repository."

git tag -a "$SAGE_VERSION" -m "$SAGE_VERSION_BANNER" \
    || die "Error tagging the repository."
