#!/usr/bin/bash -efu

# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
#
# See LICENSE for more details.
#
# Copyright: Red Hat Inc. 2023
# Author: Michal Srb <michal@redhat.com>
# Andrei Stepanov <astepano@redhat.com>

# Prepare system for install, remove, downgrade, update tests

set -x

# Source mtps-setup from $PATH
if command -v "mtps-setup" >/dev/null; then source "mtps-setup"; fi
# If previous fails source `mtps-setup` from this script dir
# shellcheck disable=SC1091
if [ -z "${YUMDNFCMD:-}" ]; then source "$(dirname "${BASH_SOURCE[0]}")/../../mtps-setup" || ( echo "Cannot source mtps-setup" >&2; exit 91 ); fi

echo "Preparing the system for testing..."

if [ -n "${FIXREPO:-}" ]; then
    echo "Ignoring \"--fixrepo\" option as it has no effect on Fedora profiles"
fi

# Add buildroot repo, if needed
if [ -n "${ENABLE_BUILD_ROOT:-}" ] && [ "${PROFILE}" != "fedora-eln" ]; then
    echo "Enabling buildroot repository..."
    FEDORA_NUMBER=$(echo "${PROFILE}" | awk -F'-' '{ print $2 }')

cat << EOF > "/etc/yum.repos.d/${PROFILE}.repo"
[${PROFILE}-buildroot]
name=${PROFILE} Buildroot
baseurl=https://kojipkgs.fedoraproject.org/repos/f${FEDORA_NUMBER}-build/latest/x86_64/
enabled=1
gpgcheck=0
skip_if_unavailable=True
EOF
fi

if [[ "$PROFILE" == "fedora-eln" ]]; then
  # Replace system repositories with a profile repo
  find "/etc/yum.repos.d/" -name "*.repo" -delete
  cp -f "$PFILE" "$REPOFILE"
  # Add buildroot repo, if needed
  dnf5 -y install dnf5-plugins  # config-manager
  if [ -n "${ENABLE_BUILD_ROOT:-}" ]; then
      dnf5 config-manager setopt eln-buildroot.enabled=1
  fi
  dnf5 repo list
# Make sure fedora and fedora-updates repos are enabled
elif [[ "$YUMDNFCMD" == "dnf5" ]]; then
  dnf5 -y install dnf5-plugins  # config-manager
  dnf5 config-manager setopt fedora.enabled=1 updates.enabled=1
  dnf5 repo list
else
  "$YUMDNFCMD" -y install dnf-plugins-core  # config-manager
  "$YUMDNFCMD" config-manager --set-enabled fedora updates
fi

echo "Recreating the DNF cache..."
"$YUMDNFCMD" clean all
"$YUMDNFCMD" makecache

echo "Installing packages required for testing..."
"$YUMDNFCMD" -y install createrepo_c which procps-ng

echo "Updating the system..."
"$YUMDNFCMD" -y upgrade
