#!/usr/bin/env bash

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

if [ "x$SAGE64" = xyes ]; then
    echo "Compiling Mercurial as 64-bit"
    if [ -z "$CFLAG64" ]; then
        CFLAG64="-m64"
    fi
    # Note that while exporting CFLAGS is redundant here,
    # exporting CXXFLAGS currently is NOT (bug in sage-env):
    CFLAGS="-O2 -g $CFLAGS $CFLAG64"; export CFLAGS
    CXXFLAGS="-O2 -g $CXXFLAGS $CFLAG64"; export CXXFLAGS
fi

# Remove existing copies of Mercurial:
rm -rf "$SAGE_LOCAL/lib/python/mercurial"

cd src

# Apply patches
for patch in ../patches/*.patch; do
    patch -p1 <"$patch"
    if [ $? -ne 0 ]; then
        echo >&2 "Error applying '$patch'"
        exit 1
    fi
done

python setup.py install --home="$SAGE_LOCAL" --force
if [ $? -ne 0 ]; then
    echo >&2 "Error building and installing Mercurial"
    exit 1
fi

mkdir -p "$SAGE_LOCAL/etc/mercurial"
cat > "$SAGE_LOCAL/etc/mercurial/hgrc" <<HEREDOC
[trusted]
users = $USER

[diff]
git = true

[extensions]
color =
mq =
pager =
rebase =
relink =

[pager]
attend = annotate, cat, diff, log, glog, qdiff
HEREDOC
if [ $? -ne 0 ]; then
    echo >&2 "Error installing custom hgrc"
    exit 1
fi

mkdir -p "$SAGE_LOCAL/etc/mercurial/hgrc.d"
cp contrib/mergetools.hgrc "$SAGE_LOCAL/etc/mercurial/hgrc.d/mergetools.rc"
if [ $? -ne 0 ]; then
    echo >&2 "Error installing mergetools.rc"
    exit 1
fi

# As a sanity check that Mercurial works, run "hg log" on the spkg
# repository and check that it works sensibly.
# This used to fail with mercurial-1.8.4 on Solaris SPARC.
cd ..
if hg log >/dev/null; then
    echo "Mercurial seems to work correctly."
else
    echo >&2 "Mercurial installed correctly, but doesn't seem to work properly."
    echo >&2 "Running 'hg log' in the directory `pwd` failed."
    exit 1
fi
