#!/bin/sh
# Talks to Meowlnir's management API.
#
# The API is not published outside the container network, so requests are made from inside the container, which ships with curl.
# The management secret is read out of the live configuration file, so that it lives in exactly one place.
#
# Usage: meowlnir-api <METHOD> <PATH> [JSON_BODY]
# Example: meowlnir-api GET /_meowlnir/v1/bots
#
# Prints the response body, followed by the HTTP status code on its own final line.

set -eu

CONFIG_FILE='{{ matrix_bot_meowlnir_config_path }}/config.yaml'
CONTAINER_NAME='matrix-bot-meowlnir'
API_BASE='http://localhost:{{ matrix_bot_meowlnir_config_meowlnir_port }}'
REQUEST_TIMEOUT='{{ matrix_bot_meowlnir_api_request_timeout_seconds }}'

if [ $# -lt 2 ]; then
	echo "Usage: $(basename "$0") <METHOD> <PATH> [JSON_BODY]" >&2
	echo "Example: $(basename "$0") GET /_meowlnir/v1/bots" >&2
	exit 2
fi

method="$1"
api_path="$2"
body="${3:-}"

# The configuration file is generated by Ansible, so its layout is predictable.
secret="$(awk '$1 == "management_secret:" { print $2; exit }' "$CONFIG_FILE" | sed 's/^"//; s/"$//')"

if [ -z "$secret" ]; then
	echo "Could not read management_secret from $CONFIG_FILE" >&2
	exit 1
fi

if [ "$secret" = 'disable' ]; then
	echo "Meowlnir's management API is disabled (management_secret is set to 'disable')" >&2
	exit 1
fi

if [ -n "$body" ]; then
	exec {{ devture_systemd_docker_base_host_command_docker }} exec "$CONTAINER_NAME" \
		curl -sS --max-time "$REQUEST_TIMEOUT" -X "$method" \
		-H "Authorization: Bearer $secret" \
		-H 'Content-Type: application/json' \
		-d "$body" \
		-w '\n%{http_code}' \
		"$API_BASE$api_path"
fi

exec {{ devture_systemd_docker_base_host_command_docker }} exec "$CONTAINER_NAME" \
	curl -sS --max-time "$REQUEST_TIMEOUT" -X "$method" \
	-H "Authorization: Bearer $secret" \
	-w '\n%{http_code}' \
	"$API_BASE$api_path"
