#!/usr/bin/env bash
set -euo pipefail

cd "$(dirname "$0")"

container_engine="${CONTAINER_ENGINE:-podman}"
case "$container_engine" in
    podman|docker) ;;
    *) printf 'Unsupported container engine: %s\n' "$container_engine" >&2; exit 2 ;;
esac

if [[ -n "${HUB_USER:-}" || -n "${HUB_TOKEN:-}" ]]; then
    : "${HUB_USER:?HUB_USER is required}"
    : "${HUB_TOKEN:?HUB_TOKEN is required}"
    auth_dir="$(mktemp -d)"
    trap 'rm -rf "$auth_dir"' EXIT
    if [[ "$container_engine" == "podman" ]]; then
        export REGISTRY_AUTH_FILE="$auth_dir/auth.json"
    else
        export DOCKER_CONFIG="$auth_dir"
    fi
    printf '%s' "$HUB_TOKEN" | "$container_engine" login hub.astra-automation.ru \
        --username "$HUB_USER" --password-stdin
fi

ansible-builder build -f execution-environment.yml \
    --container-runtime "$container_engine" \
    -t localhost/aa-ee-cli-example:1.0
if [[ "$container_engine" == "podman" ]]; then
    ansible-navigator run smoke.yml -i localhost, --mode stdout \
        --container-engine podman \
        --execution-environment-image localhost/aa-ee-cli-example:1.0 \
        --pull-policy never --playbook-artifact-enable false \
        --ssh-forward-keys false --ssh-forward-config false \
        --ssh-forward-agent false
else
    docker run --rm -e HOME=/runner \
        -v "$PWD/smoke.yml:/runner/smoke.yml:ro" \
        --entrypoint ansible-playbook localhost/aa-ee-cli-example:1.0 \
        -i localhost, -c local /runner/smoke.yml
fi
