#!/usr/bin/env bash
#
# Ansible Collection Boilerplate:
# "ap": ansible-playbook(1) wrapper script.
#

set -eu -o pipefail

# Change working directory to the base directory ...
cd "$(dirname "$0")/.." || exit 1

# Enable the Python "virtual environment" when one exists:
if [[ -r .venv/bin/activate ]]; then
	# shellcheck disable=SC1091
	. .venv/bin/activate
fi

# Get playbook name:
if [[ $# -lt 1 ]]; then
	echo "Usage: ap <playbook> [<ansible-playbook_arguments> [...]]" >&2
	echo "       ap --list" >&2
	exit 1
fi
play="$1"
shift

if [[ "${play}" == "--list" ]]; then
	# List all available playbooks
	{
		find \
			. \
			playbooks{,/deploy,/site} \
			ansible_galaxy/ansible_collections/*/*/playbooks \
			-maxdepth 1 -name '*.yml' -type f 2>/dev/null \
		| while read -r file; do
			dir=$(dirname "$file")
			name=$(basename "$file")
			name=${name%*.yml}
			case "${name}" in
				.*|galaxy|requirements)
					continue
					;;
				*)
					printf -- "- %s [%s]\n" "${name}" "${dir}"
			esac
		done || true
	} | sort -u
	exit 0
fi

# Search playbook ...
unset playbook
for dir in \
	. \
	playbooks{,/deploy,/site} \
	ansible_galaxy/ansible_collections/*/*/playbooks \
; do
	playbook="${dir}/${play}.yml"
	test -r "${playbook}" && break
	unset playbook
done

# No playbook found so far by looking in the "well known" path names and by
# appending the ".yml" extension, so use the given playbook name verbatim.
[[ -n "${playbook:-}" ]] || playbook="${play}"

# Run ansible-playbook(1):
set +u
[[ -t 1 ]] && set -x
exec ansible-playbook "${playbook}" "$@"
