#!/bin/bash

if [ "${DIB_DEBUG_TRACE:-0}" -gt 0 ]; then
    set -x
fi
set -eu
set -o pipefail

source "$(dirname $0)/../resources/package_utils.sh"

echo "START: installing MapR core repository"

get_repo_url() {
    local repo_url=""

    if [ "$DISTRO_NAME" = "ubuntu" ]; then
        repo_url="${DIB_MAPR_CORE_DEB_REPO:-http://package.mapr.com/releases/v${DIB_MAPR_VERSION}/ubuntu/mapr-v${DIB_MAPR_VERSION}GA.deb.tgz}"
    elif [ "$DISTRO_NAME" = "centos" -o "$DISTRO_NAME" = "centos7" -o "$DISTRO_NAME" = "rhel" -o "$DISTRO_NAME" = "rhel7" ]; then
        repo_url="${DIB_MAPR_CORE_RPM_REPO:-http://package.mapr.com/releases/v${DIB_MAPR_VERSION}/redhat/mapr-v${DIB_MAPR_VERSION}GA.rpm.tgz}"
    fi

    echo "$repo_url"
}

MAPR_REPO_URL="$(get_repo_url)"
MAPR_REPO_DIR="/opt/mapr-repository/core"
MAPR_REPO_NAME="mapr_core"

echo "Downloading MapR repository archive"
mkdir -p "$MAPR_REPO_DIR" && curl "$MAPR_REPO_URL" | tar -xz -C "$MAPR_REPO_DIR"

echo "Creating local repository"
create_repo "$MAPR_REPO_DIR"

echo "Adding MapR repository"
add_local_repo "$MAPR_REPO_NAME" "$MAPR_REPO_DIR"

echo "END: installing MapR core repository"
