#!/usr/bin/env bash

# Usage: ./08-wait-for-port.sh host port [max_retries] [wait_time]

LOCAL_COUNTER=0
HOST_NAME=$1
PORT=$2
MAX_RETRIES="${3:-60}"
WAIT_TIME="${4:-2}"

# Wait for a port to be available. Makes up to MAX_RETRIES requests
echo 'starting'
while ! nc -z "$HOST_NAME" "$PORT"; do
    if [[ $LOCAL_COUNTER -ge $MAX_RETRIES ]]; then
        echo "Timeout"
        exit 1
    fi
    sleep "$WAIT_TIME"
    # Increment counter inside double parens
    ((LOCAL_COUNTER++))
done
