#!/bin/sh
# Asks the homeserver who Meowlnir's appservice token belongs to.
#
# A `200` response proves the homeserver has Meowlnir's appservice registration loaded.
# A `401` (`M_UNKNOWN_TOKEN`) response means it is running without it — the condition that otherwise surfaces as Meowlnir endlessly logging "Failed to connect to homeserver".
#
# Usage: meowlnir-whoami
#
# 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'
HOMESERVER_ADDRESS='{{ matrix_bot_meowlnir_config_homeserver_address }}'
REQUEST_TIMEOUT='{{ matrix_bot_meowlnir_api_request_timeout_seconds }}'

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

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

# Runs curl inside the container, because the homeserver is only reachable over the container network.
exec {{ devture_systemd_docker_base_host_command_docker }} exec "$CONTAINER_NAME" \
	curl -sS --max-time "$REQUEST_TIMEOUT" \
	-H "Authorization: Bearer $as_token" \
	-w '\n%{http_code}' \
	"$HOMESERVER_ADDRESS/_matrix/client/v3/account/whoami"
