#!/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. 2018, 2023
# Author: Andrei Stepanov <astepano@redhat.com>

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

# This is independent script from Brew build.

: "${PROG:=${0##*/}}"

# 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
if [ -z "${YUMDNFCMD:-}" ]; then source "$(dirname "${BASH_SOURCE[0]}")/mtps-setup" || ( echo "Cannot source mtps-setup" >&2; exit 91 ); fi

msg_usage() {
    cat << EOF

Get RPM for Brew build.

Usage:
$PROG <options>

Options:
-h, --help                              display this help and exit
-v, --verbose                           turn on debug
-p, --profile=PROFILE                   use profile
-f, --fixrepo                           fix repo to specific compose ID. Resolve the latest to
-l, --list                              list available profiles
    --optrepo=REPO1 --optrepo=REPO2     use optional repos
    --optlist                           list available profiles
    --enablebuildroot                   enable buildroot repository
EOF
}

: "${DEBUG:=}"
: "${PROFILE:=}"
: "${LIST:=}"
: "${OPTLIST:=}"
: "${ENABLE_BUILD_ROOT:=}"
: "${FIXREPO:=}"
: "${PFILE:=}"

declare -a OPTREPOS=()

if ! [ -d "${PROFILES_TOPDIR:=$(rpm --eval %_datarootdir)/mini-tps/profiles/}" ]; then
    debug "Profiles dir: ${PROFILES_TOPDIR:="$PWD/profiles/"}"
fi

#opt_str="$@"
opt=$(getopt -n "$0" --options "hvfp:l" --longoptions "help,fixrepo,verbose,enablebuildroot,profile:,list,optlist,optrepo:" -- "$@")
eval set -- "$opt"
while [[ $# -gt 0 ]]; do
    case "$1" in
        -p|--profile)
            PROFILE="$2"
            shift 2
            ;;
        -l|--list)
            LIST="yes"
            shift
            ;;
        --optlist)
            OPTLIST="yes"
            shift
            ;;
        --optrepo)
            OPTREPOS+=("$2")
            shift 2
            ;;
        --enablebuildroot)
            ENABLE_BUILD_ROOT="yes"
            shift
            ;;
        -f|--fixrepo)
            FIXREPO="yes"
            shift
            ;;
        -v|--verbose)
            DEBUG="-v"
            shift
            ;;
        -h|--help)
            msg_usage
            exit 0
            ;;
        --)
            shift
            ;;
        *)
            msg_usage
            exit 1
    esac
done

# Test correct invocation
if [ -z "${LIST}${PROFILE}${OPTLIST}" ]; then
  echo "Use: $PROG -h for help."
  exit
fi

if [ -n "$LIST" ]; then
    # shellcheck disable=SC2046
    find $(find "${PROFILES_TOPDIR}" -maxdepth 1 -mindepth 1 -type d -exec echo {}/repos/ \;) -type f -name "*.repo" | sed -n -e 's/\.repo$//;s/^.*\///p'
    exit
fi

if [ -n "$OPTLIST" ]; then
    # shellcheck disable=SC2046
    find $(find "${PROFILES_TOPDIR}" -maxdepth 1 -mindepth 1 -type d -exec echo {}/optrepos/ \;) -type f -name "*.repo" | sed -n -e 's/\.repo$//;s/^.*\///p'
    exit
fi

# shellcheck disable=SC2046
# Find the repo file for given profile. We assume that repo files have unique names across all supported systems
PFILE=$(find $(find "${PROFILES_TOPDIR}" -maxdepth 1 -mindepth 1 -type d -exec echo {}/repos/ \;) -type f -name "${PROFILE}.repo")
if ! [ -f "$PFILE" ]; then
    echo "Profile \"$PROFILE\" doesn't exist."
fi
if ! [ -r "$PFILE" ]; then
    echo "Cannot read $PFILE"
    exit 1
fi
debug "Profile file: $PFILE"

# OS-specific profile directories should have names like: "rhel", "centos-stream", "fedora", etc.
OS_ID="$(basename "$(dirname "$(dirname "${PFILE}")")")"
: "${PROFILES_DIR:=$(rpm --eval %_datarootdir)/mini-tps/profiles/${OS_ID}/repos/}"
: "${OPTREPOS_DIR:=$(rpm --eval %_datarootdir)/mini-tps/profiles/${OS_ID}/optrepos/}"

if [ "$(id -u)" != "0" ]; then
    echo "Run $PROG with root privileges."
    exit 1
fi

# shellcheck disable=SC2034
REPOFILE="/etc/yum.repos.d/profile.repo"
# shellcheck disable=SC2034
REPOFILE_OPT_PREFIX="mini-tps-opt"

debug "Running prepare script: ${PREPARE_SYSTEM_SCRIPT:=$(rpm --eval %_libexecdir)/mini-tps/${OS_ID}/prepare-system}"
# shellcheck disable=SC1090
source "$PREPARE_SYSTEM_SCRIPT"
