#!/usr/bin/env bash
set -eo pipefail

ZULIP_PATH="$(dirname "$0")/../.."
ZULIP_SRV="/srv"
if [ "$TRAVIS" ] ; then
    ZULIP_SRV="/home/travis"
fi
YARN_PACKAGE_JSON="$ZULIP_SRV/zulip-yarn/package.json"
node_version=12.16.1
yarn_version=1.22.4
nvm_version=0.35.3

# This is a fix for the fact that nvm uses $HOME to determine which
# user account's home directory to ~/.config to.  Ideally, we'd have a
# more systematic fix, like using `sudo -H` everywhere.
export HOME=/root

current_node_version="none"
if node_wrapper_path="$(command -v node)"; then
    current_node_version="$(node --version)"
fi

current_yarn_version="none"
if [ -e "$YARN_PACKAGE_JSON" ]; then
    current_yarn_version=$(jq -r '.version' "$YARN_PACKAGE_JSON")
fi

if [ "$current_yarn_version" = "$yarn_version" ] && [ "$current_node_version" = "v$node_version" ] && [ -L "$node_wrapper_path" ]; then
    echo "Node version $node_version and yarn version $yarn_version are already installed."
    exit 0
fi

if [ "$current_node_version" != "v$node_version" ] || ! [ -L "$node_wrapper_path" ]; then
    export NVM_DIR=/usr/local/nvm
    # shellcheck source=/dev/null
    if ! [ -e "$NVM_DIR/nvm.sh" ] || { . "$NVM_DIR/nvm.sh"; [ "$(nvm --version)" != "$nvm_version" ]; }; then
        mkdir -p "$NVM_DIR"
        wget_opts=(-nv)
        if [ -n "${CUSTOM_CA_CERTIFICATES:-}" ]; then
            wget_opts+=(--ca-certificate "${CUSTOM_CA_CERTIFICATES}")
        fi
        wget "${wget_opts[@]}" -O- "https://raw.githubusercontent.com/nvm-sh/nvm/v$nvm_version/install.sh" | bash
        # shellcheck source=/dev/null
        . "$NVM_DIR/nvm.sh"
    fi

    nvm install "$node_version" && nvm alias default "$node_version"
    NODE_BIN="$(nvm which default)"

    # Fix messed-up uid=500 and group write bits produced by nvm
    n=${NODE_BIN%/bin/node}
    chown -R root:root "$n"
    chmod -R go-w "$n"

    # Install node symlink to /usr/local/bin
    ln -nsf "$NODE_BIN" /usr/local/bin/node
fi

# Work around the fact that apparently sudo doesn't clear the HOME
# environment variable in some cases; we don't want root
# accessing/storing yarn configuration in the non-root user's home
# directory.
export HOME=/root

# Install yarn if not installed
bash "$ZULIP_PATH/scripts/lib/third/install-yarn.sh" "$ZULIP_SRV" --version "$yarn_version"
