#!/bin/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

# Prepare environment ...
test -x "${PWD}/.venv/bin/ansible-playbook" || make "${PWD}/.venv/bin/ansible"

# Get playbook name:
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}"

# Options ...
options=("$@")

[[ -r .ansible-vault-secret ]] && options+=("--vault-password-file=.ansible-vault-secret")

# Run ansible-playbook(1):
set -x +u
"${PWD}/.venv/bin/ansible-playbook" "${playbook}" "${options[@]}"
