#!/bin/bash

set -xe

# Until we determine otherwise, assume that we are not using
# yum.repos.d, and so we do not need to add a .repo file for RHSCL.
add_rhscl=false

# Update Yum repos that point to OSE 1.2 to point to OSE 2.0.
# Assumption: Repos configuration files are named as in our installation script.
for i in openshift-client.repo openshift-jboss.repo openshift-infrastructure.repo openshift-node.repo
do
  file=/etc/yum.repos.d/$i
  if [[ -f "$file" ]]
  then
    # Note that we are using yum.repos.d, so we need to add a .repo file
    # for RHSCL later.
    add_rhscl=true

    # RHOSE from 1.1.* to 1.2
    sed -i "$file" -e 's/1\.2\(\.[xz]\)\?/2.0/'

    # Some puddles use datestamps to reference puddle.  Here we ensure they are
    # using the 'latest' symlink since we know that will always exist
    sed -i "$file" -e 's/[[:digit:]]\{4\}-[[:digit:]]\{2\}-[[:digit:]]\{2\}\.[[:digit:]]\{1,2\}/latest/'
  fi
done

# Configure the RHSCL Yum repo if it's not already configured.
if [[ "$add_rhscl" = true ]] && ! [[ -e /etc/yum.repos.d/rhscl.repo ]]
then
  # Try to guess the location of the RHSCL repo from the location of the
  # JBoss repo.  If there is no JBoss repo configured, try the OSE
  # infrastructure and node repos in turn.
  for i in openshift-jboss.repo openshift-infrastructure.repo openshift-node.repo
  do
    file=/etc/yum.repos.d/$i
    if [[ -f "$file" ]]
    then
      repo_base="$(sed -n -e '/^baseurl=/ s,.*\(http://.*/x86_64\).*,\1,p' $file)"
      [[ -n "$repo_base" ]] && break 2
    fi
  done

  if [[ -z "$repo_base" ]]
  then
    echo 'WARNING: You must configure the Yum repo for RHSCL.'
    exit 1
  fi

  cat <<YUM > /etc/yum.repos.d/rhscl.repo
[rhscl]
name=rhscl
baseurl=${repo_base}/rhscl/1/os/
enabled=1
priority=3
gpgcheck=0

YUM
fi

yum clean all
