# Tiny Cloud - Azure Init Functions
# vim:set filetype=sh:
# shellcheck shell=sh

: "${AZURE_WIRESERVER:=168.63.129.16}"
: "${AZURE_READY_ATTEMPTS:=5}"
: "${AZURE_READY_RETRY_DELAY:=5}"

azure_goalstate_value() {
	printf '%s' "$2" | tr -d '\r\n' |
		sed -n "s|.*<$1>\([^<]*\)</$1>.*|\1|p"
}

azure_report_ready() {
	local endpoint goalstate incarnation container_id instance_id health
	endpoint="http://$AZURE_WIRESERVER/machine"
	goalstate=$(
		$MOCK wget --quiet --output-document - --timeout 5 \
			--header "x-ms-version: 2012-11-30" \
			"$endpoint?comp=goalstate"
	) || return

	incarnation=$(azure_goalstate_value Incarnation "$goalstate")
	container_id=$(azure_goalstate_value ContainerId "$goalstate")
	instance_id=$(azure_goalstate_value InstanceId "$goalstate")
	[ -n "$incarnation" ] && [ -n "$container_id" ] &&
		[ -n "$instance_id" ] || return 1
	case "$incarnation$container_id$instance_id" in
		*[!A-Za-z0-9._-]*) return 1;;
	esac

	health="<Health><GoalStateIncarnation>$incarnation</GoalStateIncarnation><Container><ContainerId>$container_id</ContainerId><RoleInstanceList><Role><InstanceId>$instance_id</InstanceId><Health><State>Ready</State></Health></Role></RoleInstanceList></Container></Health>"
	$MOCK wget --quiet --output-document /dev/null --timeout 5 \
		--header "x-ms-version: 2012-11-30" \
		--header "x-ms-agent-name: tiny-cloud" \
		--header "Content-Type: text/xml;charset=utf-8" \
		--post-data "$health" "$endpoint?comp=health"
}

init__report_provisioning_ready() {
	local attempt=1
	while ! azure_report_ready; do
		[ "$attempt" -ge "$AZURE_READY_ATTEMPTS" ] && return 1
		sleep "$AZURE_READY_RETRY_DELAY"
		attempt=$((attempt + 1))
	done
}

finalize_init_actions() {
	INIT_ACTIONS_FINAL="$(
		insert_before bootstrap_complete report_provisioning_ready \
			$INIT_ACTIONS_FINAL
	)"
}
