#!/bin/bash

set -eu
set -o pipefail

SCRIPT_NAME=$(basename $0)

function show_options {
    echo "Usage: $SCRIPT_NAME [<nodes>] [options]"
    echo
    echo "Waits for \`nova hypervisor-stats\` to show some memory + vcpus are available."
    echo
    echo "Positional arguments:"
    echo "      nodes           -- The number of nodes to wait for, defaults to 1."
    echo "      memory          -- The amount of memory to wait for in MB,"
    echo "                         defaults to the amount of memory for the"
    echo "                         baremetal flavor times the number of nodes."
    echo "      vcpus           -- The number of vcpus to wait for,"
    echo "                         defaults to the number of vcpus for the"
    echo "                         baremtal flavor times the number of nodes."
    echo
    echo "Options:"
    echo "      -h / --help    -- this help"
    echo
    exit $1
}

TEMP=$(getopt -o h -l help -n $SCRIPT_NAME -- "$@")
if [ $? != 0 ]; then
    echo "Terminating..." >&2
    exit 1
fi

# Note the quotes around `$TEMP': they are essential!
eval set -- "$TEMP"

while true ; do
    case "$1" in
        -h | --help) show_options 0;;
        --) shift ; break ;;
        *) echo "Error: unsupported option $1." ; exit 1 ;;
    esac
done

EXPECTED_NODES=${1:-1}
EXPECTED_MEM=${2:-""}
EXPECTED_VCPUS=${3:-""}

# NOTE(bnemec): If/when we have more flavors, this will need
# to be expanded.
if [ -z "$EXPECTED_VCPUS" ]; then
    FLAVOR=$(nova flavor-show baremetal)
    VCPUS=$(echo "$FLAVOR" | awk '$2=="vcpus" { print $4 }')
    EXPECTED_VCPUS=$(($VCPUS*$EXPECTED_NODES))
fi

if [ -z "$EXPECTED_MEM" ]; then
    FLAVOR=$(nova flavor-show baremetal)
    MEM=$(echo "$FLAVOR" | awk '$2=="ram" { print $4 }')
    EXPECTED_MEM=$(($MEM*$EXPECTED_NODES))
fi

nova hypervisor-stats | awk '
$2=="count" && $4 >= '"$EXPECTED_NODES"' { c++ };
$2=="memory_mb" && $4 >= '"$EXPECTED_MEM"' { c++ };
$2=="vcpus" && $4 >= '"$EXPECTED_VCPUS"' { c++ };
END { if (c != 3) exit 1 }'
