#!/bin/bash
#
# description=List hosts, tags, etc. used in the project.
#

set -euo pipefail

# Show usage information on stderr.
#
Usage_Exit() {
	{
		echo "ansible-boilerplate list <subcommand>"
		echo
		echo   "  groups [<limit_pattern>]"
		echo   "		Show all or a subset of host groups defined in the inventory"
		echo   "  hosts [<limit_pattern>]"
		echo   "		Show all or a subset of hosts defined in the inventory"
		echo   "  plays		Show all available playbooks"
		echo   "  tags		Show all tags used in the tasks"
		echo
	} >&2
	exit "${1:-1}"
}

Groups() {
	[[ $# -le 1 ]] || Usage_Exit

	args=()
	[[ -r .ansible-vault-secret ]] && args+=("--vault-password-file=.ansible-vault-secret")
	[[ $# -ge 1 ]] && args+=(-l "$1")

	ansible-inventory \
		--list "${args[@]}" \
		| jq -r "keys | .[]" \
		| grep -Ev '^_meta$' \
		| sort -u
}

Hosts() {
	[[ $# -le 1 ]] || Usage_Exit

	args=()
	[[ -r .ansible-vault-secret ]] && args+=("--vault-password-file=.ansible-vault-secret")
	[[ $# -ge 1 ]] && args+=(-l "$1")

	ansible-inventory \
		--list "${args[@]}" |
		jq ".[].hosts" |
		sed -Ene 's/^.*"(.*)",?/\1/p' |
		sort -u
}

Plays() {
	[[ $# -eq 0 ]] || Usage_Exit
	./bin/ap --list | sed -e 's/^- //' | sort
}

Tags() {
	[[ $# -eq 0 ]] || Usage_Exit

	(
		find ./ -maxdepth 2 -name 'site.yml' -print0 2>/dev/null || true
		find ./play*/ -maxdepth 2 -name '*.yml' -a -not -name 'site.yml' 2>/dev/null | grep -Fv '/site/' | tr '\n' '\0' || true
		find ./ansible_galaxy/ -maxdepth 4 -name 'play*' -type d 2>/dev/null | xargs -I _ find _ -maxdepth 1 -name '*.yml' -print0 2>/dev/null
	) |
		xargs -0 -I _ ./bin/ap _ --list-tags |
		sed -En -e 's/.*TAGS: \[(.*)\].*/\1/gp' |
		sed -e 's/, /\n/g' -e '/^$/d' |
		sort -u
}

cmd="${1-}"
[[ $# -gt 0 ]] && shift

case "${cmd}" in
"groups")
	Groups "$@"
	;;
"hosts")
	Hosts "$@"
	;;
"plays" | "playbooks")
	Plays "$@"
	;;
"tags")
	Tags "$@"
	;;
"help" | "--help")
	Usage_Exit 0
	;;
*)
	Usage_Exit
	;;
esac
exit $?
