#!/bin/bash

set -ex

# The default version will be 1.2
OSE_VERSION=${DIB_OSE_VERSION:="1.2"}

if [ "${OSE_VERSION}" == "1.2" ]; then
  if [ -z "${DIB_RHSM_OSE_POOL:-}" ]; then
  cat > /etc/yum.repos.d/openshift-client.repo <<YUM
[openshift_client]
name=OpenShift Client
baseurl=${DIB_CONF_REPO_BASE}/Client/x86_64/os/
enabled=1
gpgcheck=1
priority=1

YUM

  cat > /etc/yum.repos.d/openshift-infrastructure.repo <<YUM
[openshift_infrastructure]
name=OpenShift Infrastructure
baseurl=${DIB_CONF_REPO_BASE}/Infrastructure/x86_64/os/
enabled=1
gpgcheck=1
priority=1

YUM
  fi
else
  if [ -n "${DIB_CONF_REPO_BASE}" ]; then
      cat <<YUM > /etc/yum.repos.d/openshift.repo
[openshift_client]
name=OpenShift Client
baseurl=${DIB_CONF_REPO_BASE}/RHOSE-CLIENT-2.0/x86_64/os/
enabled=1
gpgcheck=1
priority=10

[openshift_infrastructure]
name=OpenShift Infrastructure
baseurl=${DIB_CONF_REPO_BASE}/RHOSE-INFRA-2.0/x86_64/os/
enabled=1
gpgcheck=1
priority=10

YUM
  fi
fi

# DIB_REG_TYPE of rhn or rhsm should be used if oo-admin-yum-validator is to be triggered
yum install -y yum-plugin-priorities
if [ -n "${DIB_REG_TYPE}" ]; then
  # oo-admin-check-sources will ship with 2.0 however it is still compatible with OSE 1.2
  curl -L https://api.github.com/repos/openshift/openshift-extras/tarball/master | tar -xvz
  pushd openshift-openshift-extras*/admin/yum-validator
    VALIDATOR_ARGS=" --role=broker --fix-all"
    if [ -n ${DIB_YUM_VALIDATOR_VERSION} ]; then
      VALIDATOR_ARGS+=" --oo-version ${DIB_YUM_VALIDATOR_VERSION}"
    fi
    ./oo-admin-yum-validator ${VALIDATOR_ARGS} || ./oo-admin-yum-validator ${VALIDATOR_ARGS}
  popd
  rm -rf openshift-openshift-extras*
fi

OSE_PACKAGES="yum-plugin-priorities openshift-origin-broker openshift-origin-broker-util rubygem-openshift-origin-msg-broker-mcollective rubygem-openshift-origin-auth-remote-user rubygem-openshift-origin-dns-nsupdate openshift-origin-console rhc activemq mongodb mongodb-server bind bind-utils mod_auth_kerb ntp ntpdate wget "


OSE_V1_PACKAGES="mcollective-client "

OSE_V2_PACKAGES="ruby193-mcollective-client rubygem-openshift-origin-admin-console "

if [ $OSE_VERSION == "1.2" ]; then
  OSE_PACKAGES+=OSE_V1_PACKAGES
else
  OSE_PACKAGES+=OSE_V2_PACKAGES
fi

yum update -y
install-packages $OSE_PACKAGES --skip-broken
