#!/bin/bash
# © Copyright EnterpriseDB UK Limited 2015-2023 - All rights reserved.
#
# This is a wrapper for bin/ansible that sets various environment
# variables before invoking the real executable (which must be in
# our venv).

IFS=$' \t\n'
set -eu

# If $TPA_DIR is not already set, we guess TPA_DIR based on $0 (so that
# a git checkout takes precedence over a package installation), or use
# /opt/EDB/TPA if it exists.

TOP=/opt/EDB/TPA
if [[ -z "${TPA_DIR:-}" ]]; then
    SRC=$(dirname "$0")/..
    type realpath &>/dev/null && SRC=$(realpath "$SRC")
    if [[ -d $SRC/roles ]]; then
        TOP=$SRC
    fi
fi

export TPA_DIR=${TPA_DIR:-$TOP}
TPA_VENV=${TPA_VENV:-$TPA_DIR/tpa-venv}
VENV_BIN="$TPA_VENV/bin"

# Set ANSIBLE_LOG_PATH, ANSIBLE_CONFIG, and ANSIBLE_INVENTORY to our
# versions if they are not already set.

export ANSIBLE_LOG_PATH=${ANSIBLE_LOG_PATH:-./ansible.log}
export ANSIBLE_CONFIG=${ANSIBLE_CONFIG:-$TPA_DIR/ansible/ansible.cfg}
export ANSIBLE_INVENTORY=${ANSIBLE_INVENTORY:-$TPA_DIR/ansible/hosts}

# Append our directories to various search paths.
#
# In exceptional situations, this allows you to do things like set
# ANSIBLE_ROLES_PATH to override a specific TPA-provided role.

export ANSIBLE_LIBRARY=${ANSIBLE_LIBRARY:+$ANSIBLE_LIBRARY:}$TPA_DIR/library
export ANSIBLE_ROLES_PATH=${ANSIBLE_ROLES_PATH:+$ANSIBLE_ROLES_PATH:}$TPA_DIR/roles
export ANSIBLE_TEST_PLUGINS=${ANSIBLE_TEST_PLUGINS:+$ANSIBLE_TEST_PLUGINS:}$TPA_DIR/lib/test_plugins
export ANSIBLE_ACTION_PLUGINS=${ANSIBLE_ACTION_PLUGINS:+$ANSIBLE_ACTION_PLUGINS:}$TPA_DIR/lib/action_plugins
export ANSIBLE_FILTER_PLUGINS=${ANSIBLE_FILTER_PLUGINS:+$ANSIBLE_FILTER_PLUGINS:}$TPA_DIR/lib/filter_plugins
export ANSIBLE_LOOKUP_PLUGINS=${ANSIBLE_LOOKUP_PLUGINS:+$ANSIBLE_LOOKUP_PLUGINS:}$TPA_DIR/lib/lookup_plugins
export ANSIBLE_CALLBACK_PLUGINS=${ANSIBLE_CALLBACK_PLUGINS:+$ANSIBLE_CALLBACK_PLUGINS:}$TPA_DIR/lib/callback_plugins
export ANSIBLE_COLLECTIONS_PATHS=${ANSIBLE_COLLECTIONS_PATHS:+$ANSIBLE_COLLECTIONS_PATHS:}$TPA_VENV/collections

# This script may be invoked through symlinks as ansible, ansible-vault,
# or ansible-playbook. We try to run ansible from our venv, or fail if
# we can't find it there.

cmd=$(basename "$0")

if [[ ! -x $VENV_BIN/ansible ]]; then
    echo -n "ERROR: ansible not found" >&2
    if command -v ansible &>/dev/null; then
        echo " (won't use $(command -v ansible); did you run tpaexec setup?)" >&2
    else
        echo " (did you run tpaexec setup?)" >&2
    fi
    exit 1
fi

PATH="$VENV_BIN:$PATH" "$VENV_BIN/$cmd" "$@"
