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

version=16.15.1
arch="$(uname -m)"

case $arch in
    x86_64)
        tarball="node-v$version-linux-x64.tar.xz"
        sha256=b749f7a76e56dfd6dfb8a910b8a2a871159661557680aa95acf13c9514422c12
        ;;

    aarch64)
        tarball="node-v$version-linux-arm64.tar.xz"
        sha256=ddd18ba09cfa937f75123a9d69256d44386ff1b9c0d12fa4b3f9ce0b0d121d9d
        ;;
esac

check_version() {
    out="$(node --version)" && [ "$out" = "v$version" ]
}

if ! check_version; then
    tmpdir="$(mktemp -d)"
    trap 'rm -r "$tmpdir"' EXIT
    cd "$tmpdir"
    curl_opts=(-fLO)
    if [ -n "${CUSTOM_CA_CERTIFICATES:-}" ]; then
        curl_opts+=(--cacert "${CUSTOM_CA_CERTIFICATES}")
    fi
    curl "${curl_opts[@]}" "https://nodejs.org/dist/v$version/$tarball"
    sha256sum -c <<<"$sha256 $tarball"
    rm -rf /srv/zulip-node
    mkdir -p /srv/zulip-node
    tar -xJf "$tarball" --no-same-owner --strip-components=1 -C /srv/zulip-node
    ln -sf /srv/zulip-node/bin/{node,npm,npx} /usr/local/bin
    rm -rf /usr/local/nvm
    check_version
fi
