#!/bin/bash
#
# Copyright 2014 Hewlett-Packard Development Company, L.P.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.

set -eu

SCRIPT_NAME=$(basename $0)

USE_WALLTIME="-l"
if [ -n "$1" -a "$1" = "-w" ]; then
    USE_WALLTIME="-w"
    shift 1
fi

LOOPS=${1:-""}
SLEEPTIME=${2:-""}
STACK_NAME=${3:-""}
if [ -z "$LOOPS" -o -z "$SLEEPTIME" -o -z "$STACK_NAME" ]; then
    echo "Usage: $SCRIPT_NAME [-w] LOOPS_NUMBER SLEEP_TIME STACK_NAME"
    exit 1
fi

SUCCESSFUL_MATCH_OUTPUT="(CREATE|UPDATE)_COMPLETE"
FAIL_MATCH_OUTPUT="(CREATE|UPDATE)_FAILED"


wait_for $USE_WALLTIME $1 --delay $2 \
    --success-match $SUCCESSFUL_MATCH_OUTPUT \
    --fail-match $FAIL_MATCH_OUTPUT -- \
    "heat stack-show $STACK_NAME | awk '/stack_status / { print \$4 }'"
