#!/usr/bin/env bash

# Copyright 2024 The Kubernetes Authors.
#
# 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 -uo pipefail

# Global vars to be used
# shellcheck source=stop
source "$(dirname "${BASH_SOURCE[0]}")"/stop

JAEGER_IMG="jaegertracing/all-in-one:1.52"

echo "Starting $JAEGER_CTR"
"$CONTAINER_RUNTIME" run -d --rm --network host --name "$JAEGER_CTR" "$JAEGER_IMG"

PORT=14250
MAX_CNT=100
for ((i = 0; i <= "$MAX_CNT"; i++)); do
    if netstat -tuplen 2>/dev/null | grep -q "$PORT .* LISTEN"; then
        break
    fi

    if [[ $i == "$MAX_CNT" ]]; then
        echo "Giving up"
        exit 1
    fi

    echo "Waiting for gRPC port $PORT to listen… ($i)"
    sleep 3
done

echo "Everything is ready, open http://localhost:16686 to access jaeger"
