#!/usr/bin/bash -efu

RET_NO_COMPOSE_ID=10

echo "Setting up RHEL internal YUM repos for selected profile"
# Replace system repositories with a profile repo
find "/etc/yum.repos.d/" -name "*.repo" -delete
declare -a INSTALLED_REPO_FILES=("$REPOFILE")
cp -f "$PFILE" "$REPOFILE"
if [ ${#OPTREPOS[@]} -ne 0 ]; then
    declare -i optindex=0
    for opt in "${OPTREPOS[@]}"; do
        OPTFILE_IN="$OPTREPOS_DIR/${opt}.repo"
        debug "Using opt repo: $OPTFILE_IN"
        if ! [ -r "$OPTFILE_IN" ]; then
            echo "Cannot read $OPTFILE_IN"
            exit 1
        fi
        OPTFILE_OUT="/etc/yum.repos.d/${REPOFILE_OPT_PREFIX}-${optindex}.repo"
        cp "$OPTFILE_IN" "$OPTFILE_OUT"
        INSTALLED_REPO_FILES+=("$OPTFILE_OUT")
        optindex+=1
    done
fi
if [ -n "$FIXREPO" ]; then
    for repofile in "${INSTALLED_REPO_FILES[@]}"; do
        composeid_url="$(cat "$repofile" | \
            sed -n -e '0,/baseurl/{ /baseurl/ s/^baseurl[[:space:]]*=[[:space:]]*//p }' | \
            sed -n -e 's/\(latest[^/]\+\).*$/\1\/COMPOSE_ID/p')"
        set +e
        COMPOSEID="$(curl --retry 5 --insecure --fail --location --show-error "$composeid_url")"
        set -e
        if [[ -z "$COMPOSEID" ]]; then
            echo "Failed to get compose id from $composeid_url"
            exit $RET_NO_COMPOSE_ID
        fi
        echo "Compose ID: $COMPOSEID"
        THELATESTDIR="$(cat "$repofile" | sed -n -e '0,/baseurl/{ /baseurl/ s/^baseurl[[:space:]]*=[[:space:]]*//p }' | grep -oE 'latest-[^/]+')"
        echo "Replacing $THELATESTDIR with $COMPOSEID in $repofile"
        sed -i -e "s/$THELATESTDIR/$COMPOSEID/g" "$repofile"
    done
fi

yum -y install yum-utils  # yum-config-manager, repoquery
yum-config-manager --disable '*'
declare -a yumrepos
for repofile in "${INSTALLED_REPO_FILES[@]}"; do
    yumrepos=($(cat "$repofile" | sed -n -e '/buildroot/d' -e '/^\[/p' | tr -d '[]'))
    yum-config-manager --enable "${yumrepos[@]}"
done

if [ -n "$ENABLE_BUILD_ROOT" ]; then
    buildroot_repo=$(cat "$REPOFILE" | sed -n -e '/^\[/{/buildroot/p}' | tr -d '[]')
    yum-config-manager --enable "$buildroot_repo"
fi

echo "Installing required packages for testing"
yum -y install createrepo_c || yum -y install createrepo
yum -y install procps-ng || yum -y install procps
yum -y install which

yum -y upgrade
yum clean all
yum makecache
