#!/bin/bash

set -e

if [ ! -f ./_mongodb_os_dist_ver.bash ] || \
   [ ! -d ./binary-tars ]; then
    echo "INSTALL.sh must be run from the extension's top-level directory." >&2
    exit 1
fi

. ./_mongodb_os_dist_ver.bash

MONGODB_ARCHIVE="mongodb-${mongodb_os_dist_ver}.tgz"
MONGODB_DIRECTORY="mongodb-${mongodb_os_dist_ver}"
MONGOSH_ARCHIVE="mongosh-${mongosh_os_ver}.tgz"
MONGOSH_DIRECTORY="mongosh-${mongosh_os_ver}"

install_archive()
{
    archive=$1
    directory=$2
    description=$3

    if [ -d "$directory" ]; then
        echo "$description is already installed in:"
        echo "  $directory"
        return 0
    fi

    if [ ! -f "$archive" ]; then
        echo "Missing $description archive:" >&2
        echo "  $archive" >&2
        return 1
    fi

    echo "Installing $description from:"
    echo "  $archive"
    tar xzf "$archive"

    if [ ! -d "$directory" ]; then
        echo "The archive did not create the expected directory:" >&2
        echo "  $directory" >&2
        exit 1
    fi
}

MONGODB_ARCHIVE_PATH="binary-tars/$MONGODB_ARCHIVE"
MONGOSH_ARCHIVE_PATH="binary-tars/$MONGOSH_ARCHIVE"

# The Debian 8 MongoDB archive is too large for the current SVN server limit.
# Download it directly when that build is selected and no local copy exists.
if [ "$MONGODB_ARCHIVE" = "mongodb-linux-x86_64-debian81-4.0.28.tgz" ] && \
   [ ! -f "$MONGODB_ARCHIVE_PATH" ]; then
    command -v curl >/dev/null 2>&1 || {
        echo "curl is required to download $MONGODB_ARCHIVE." >&2
        exit 1
    }

    echo "Downloading legacy MongoDB archive:"
    echo "  $MONGODB_ARCHIVE"
    curl -fL \
        --output "$MONGODB_ARCHIVE_PATH" \
        "https://fastdl.mongodb.org/linux/$MONGODB_ARCHIVE"
fi

if ! install_archive "$MONGODB_ARCHIVE_PATH" "$MONGODB_DIRECTORY" "MongoDB"; then
    cat >&2 <<EOF

For MongoDB Community Server releases see:
  https://www.mongodb.com/try/download/community-edition/releases
  https://www.mongodb.com/try/download/community-edition/releases/archive

Copy the selected archive to:
  $MONGODB_ARCHIVE_PATH
EOF
    exit 1
fi

if ! install_archive "$MONGOSH_ARCHIVE_PATH" "$MONGOSH_DIRECTORY" "mongosh"; then
    cat >&2 <<EOF

For MongoDB Shell releases see:
  https://github.com/mongodb-js/mongosh/releases

Copy the selected archive to:
  $MONGOSH_ARCHIVE_PATH
EOF
    exit 1
fi

cat <<'EOF'

Installation complete.

Choose exactly one server mode:

Standalone server:
  cp _mongodb_standalone_setup.bash.in _mongodb_standalone_setup.bash

Sharded cluster:
  cp _mongodb_cluster_setup.bash.in _mongodb_cluster_setup.bash
  # Edit the copied cluster file for the installation.

Then run:
  source ./SETUP.bash
EOF
