#!/bin/bash

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

VERSIONS_PY="$(dirname $0)/../resources/versions.py"

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

echo "START: installing MapR ecosystem repository"

get_repo_url() {
    local repo_url=""

    if [ "$DISTRO_NAME" = "ubuntu" ]; then
        case "$DIB_MAPR_VERSION" in
            "5.1.0")
                repo_url="${DIB_MAPR_ECO_DEB_REPO:-http://package.mapr.com/releases/ecosystem-5.x/ubuntu binary/}"
            ;;
            "5.2.0")
                repo_url="${DIB_MAPR_ECO_DEB_REPO:-http://package.mapr.com/releases/MEP/MEP-2.0.0/ubuntu/ binary trusty}"
            ;;
        esac
    elif [ "$DISTRO_NAME" = "centos7" -o "$DISTRO_NAME" = "rhel7" ]; then
        case "$DIB_MAPR_VERSION" in
            "5.1.0")
                repo_url="${DIB_MAPR_ECO_RPM_REPO:-http://package.mapr.com/releases/ecosystem-5.x/redhat}"
            ;;
            "5.2.0")
                repo_url="${DIB_MAPR_ECO_RPM_REPO:-http://package.mapr.com/releases/MEP/MEP-2.0.0/redhat}"
            ;;
        esac
    fi

    echo "$repo_url"
}

RPM_REPO="${DIB_MAPR_ECO_RPM_REPO:-}"
DEB_REPO="${DIB_MAPR_ECO_DEB_REPO:-}"

MAPR_REPO_DIR="/opt/mapr-repository/ecosystem"
MAPR_REPO_URL="$(get_repo_url)"
MAPR_REPO_NAME="mapr_ecosystem"
MAPR_PKG_GROUPS="$(dirname $0)/../resources/packages.json"

if [ -f $(dirname $0)/../resources/spec_${DIB_MAPR_VERSION}_${DISTRO_NAME}.json ]; then
    MAPR_SPEC="$(dirname $0)/../resources/spec_${DIB_MAPR_VERSION}_${DISTRO_NAME}.json"
else
    MAPR_SPEC="$(dirname $0)/../resources/spec_${DIB_MAPR_VERSION}.json"
fi

echo "Creating local MapR ecosystem repository"
localize_repo "$MAPR_REPO_NAME" "$MAPR_REPO_URL" "$MAPR_PKG_GROUPS" "$MAPR_SPEC" "$MAPR_REPO_DIR"
echo $MAPR_SPEC

echo "END: installing MapR ecosystem repository"
