#!/bin/bash -eu
# This file is meant to be source'd by other scripts

SCRIPTDIR="$(dirname -- "$(readlink -f "${BASH_SOURCE[0]}")")"

IMAGE_REPO="quay.io/ansible-freeipa/upstream-tests"

# shellcheck source=utils/shfun
. "${SCRIPTDIR}/shfun"

stop_container() {
    local scenario=${1}
    log none "Stopping container..."
    quiet "${engine}" stop "${scenario}"
    log none "Removing container..."
    quiet "${engine}" rm "${scenario}"
}

# Prepare container
prepare_container() {
    local container_id container_status hostname scenario
    local IMAGE_TAG img_id CONFIG
    container_id=""
    container_status=("-f" "status=created" "-f" "status=running")
    hostname="${IPA_HOSTNAME:-"ipaserver.test.local"}"
    scenario="${1:-${scenario:-"freeipa-tests"}}"
    IMAGE_TAG="${2:-${IMAGE_TAG:-fedora-latest}}"
    [ -n "${scenario}" ] && container_id="$(${engine} ps --all -q -f "name=${scenario}" "${container_status[@]}")"
    if [ -z "${container_id}" ]
    then
        # Retrieve image and start container.
        log info "Pulling FreeIPA image '${IMAGE_REPO}:${IMAGE_TAG}'..."
        img_id=$(${engine} pull -q "${IMAGE_REPO}:${IMAGE_TAG}")
        log debug "Hostname: ${hostname}"
        log info "Creating container..."
        CONFIG="--systemd true --hostname ${hostname} --memory ${MEMORY}g --memory-swap -1 --no-hosts"
        [ -n "${scenario}" ] && CONFIG="${CONFIG} --name ${scenario}"
        # shellcheck disable=SC2086
        container_id=$(${engine} create ${CONFIG} "${img_id}" || die "Cannot create container")
        log none "CONTAINER: ${container_id}"
    fi
    export scenario="${scenario:-$(${engine} ps -q --format "{{.Names}}" --filter "id=${container_id}" "${container_status[@]}")}"
    log debug "Prepared container: ${scenario}"
}

start_container() {
    local scenario="${1:-${scenario}}"
    log info "Starting container for ${scenario}..."
    "${engine}" start "${scenario}"
}

if [ -z "$(command -v podman)" ]
then
    engine="docker"
    engine_collection="community.docker"
else
    engine="podman"
    engine_collection="containers.podman"
fi

export engine engine_collection
