#!/usr/bin/env bash

# spkg-install file for sage root repo.

create_hgrc() {
# Create an appropriate hgrc file for the target
cat > "$TARGET/.hg/hgrc" <<"HEREDOC"
[diff]
git = true
HEREDOC
}

CUR=`pwd`

# Remove the spkg/base repository, this is needed for upgrading from
# Sage versions 4.x, see Trac #11073.
# Also remove files for "dir" (see #12631) and "bzip2" (see #12102),
# which are no longer base packages.
cd "$SAGE_ROOT/spkg/base" && \
rm -rf .hg* json_bundle.py stdint.h_Solaris9 sage-* text-* *.sh dir-* bzip2-* README.txt

TARGET="$SAGE_ROOT"

cd "$TARGET"

# Check whether there is a valid Mercurial repository in $SAGE_ROOT
if [ -d .hg ]; then

    # Merge the repository, rather than overwrite changes that the
    # user may have made.
    hg incoming "$CUR" >/dev/null
    status=$?
    if [ $status -eq 1 ]; then
        # No changes to pull
        create_hgrc
        exit 0
    fi
    if [ $status -ne 0 ]; then
        echo "Error with Sage root repository: 'hg incoming' failed."
        exit 1
    fi
    # $? = 0: There are changes to pull.
    # First check in any changes.

    hg commit -u "Sage (during sage -upgrade)"
    status=$?
    if [ $status -ne 0 -a $status -ne 1 ]; then
        echo "Committing changes failed"
        exit 1
    fi
    hg pull "$CUR" || { echo "Pulling from repo failed"; exit 1; } 
    hg merge tip
    hg commit -m "Check-in during upgrade of Sage" -u "Sage"
    status=$?
    if [ $status -ne 0 -a $status -ne 1 ]; then
        echo "Checking in new repo failed"
        exit 1
    fi
    hg update || { echo "'hg update' failed"; exit 1; }

else

    # Initial install.  First get rid of "makefile" (since it's been
    # renamed to "Makefile" in the repo, and if both "makefile" and
    # "Makefile" are present, the former gets used).
    rm -f makefile

    # Now just copy all the files over.
    cd "$CUR"
    cp -pR .hg* COPYING.txt README.txt sage Makefile spkg "$TARGET"
    if [ $? -ne 0 ]; then
        echo "Root repo: Error copying files from Sage root repo to $TARGET"
        exit 1
    fi
fi

create_hgrc
