#!/usr/bin/env bash

set +o xtrace
set -o nounset
set -o errexit
set -o pipefail
set -o noglob

export LC_ALL=C LANG=C

function usage {
	cat <<-EOF

	 Usage: $0 <resource_group_name> <status | start | stop>

	EOF

	exit 1
}

if (($# != 2)); then
	usage
fi

RESOURCE_GROUP_NAME="$1"
ACTION="$2"

case "$ACTION" in
status)
	az vm list \
		--show-details \
		--output table \
		--resource-group "$RESOURCE_GROUP_NAME" \
		--query "[].{name:name,private_IP:privateIps,public_IP:publicIps,status:powerState}"
	;;
start)
	for VM_TYPE in mgt mdt ost worker; do
		az vm list \
			--show-details \
			--output tsv \
			--resource-group "$RESOURCE_GROUP_NAME" \
			--query "[?tags.lustre_type=='$VM_TYPE' && powerState=='VM deallocated'].{name:name}" | \
			while read -r VM_NAME; do
				echo "Start $VM_TYPE host $VM_NAME"
				az vm start --resource-group "$RESOURCE_GROUP_NAME" --name "$VM_NAME"
			done
	done
	;;
stop)
	for VM_TYPE in worker ost mdt mgt; do
		az vm list \
			--show-details \
			--output tsv \
			--resource-group "$RESOURCE_GROUP_NAME" \
			--query "[?tags.lustre_type=='$VM_TYPE' && powerState=='VM running'].{name:name}" | \
			while read -r VM_NAME; do
				echo "Stop $VM_TYPE host $VM_NAME"
				az vm deallocate --resource-group "$RESOURCE_GROUP_NAME" --name "$VM_NAME"
			done
	done
	;;
*)
	usage
	;;
esac
