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

nodejs_ver=`grep -o "[0-9]\+\.[0-9]\+\.[0-9]\+" package-version.txt`

if [ $? -ne 0 ]; then
    echo "Error determining which nodejs version to install ... exiting"
    exit 1
fi

nodeenv_dir="$SAGE_LOCAL/share/nodejs/$nodejs_ver"
nodeenv_activate="$nodeenv_dir/bin/activate"

echo "Will use/install nodejs in nodeenv located at $nodeenv_dir ..."

if [ ! -f "$nodeenv_activate" ]; then
    # The nodeenv may not exist, or it may exist but installing nodejs into
    # it previously failed, so --force to cover both cases.
    nodeenv --force --verbose --node="$nodejs_ver" "$nodeenv_dir"

    if [ $? -ne 0 ]; then
        echo "Error installing nodejs ... exiting"
        exit 1
    fi
fi

. "$nodeenv_activate"

if [ $? -ne 0 ]; then
    echo "Error activating nodeenv containing nodejs ... exiting"
    exit 1
fi

active_ver=`node --version | grep -o "[0-9]\+\.[0-9]\+\.[0-9]\+"`

if [ $? -ne 0 ]; then
    echo "Error determining which nodejs version is active ... exiting"
    deactivate_node
    exit 1
fi

deactivate_node

if [ ! "$nodejs_ver" = "$active_ver" ]; then
    echo "Wrong version of nodejs was activated ... exiting"
    echo "Expected $nodejs_ver but found $active_ver"
    exit 1
fi

ln -sf "$nodeenv_activate" "$SAGE_LOCAL/share/nodejs/activate"
