#!/bin/sh -eu
# dev/ssh-wait.sh: Wait for SSH to become available on sydfuzz VM.
# Used by `make kcovup'.
#
# Copyright (c) 2026 Ali Polatel <alip@chesswob.org>
# SPDX-License-Identifier: GPL-3.0

set -eu

HOST="${1:-127.0.0.1}"
PORT="${2:-10022}"
USER="${3:-root}"
TIMEOUT="${3:-60}"
INTERVAL=2

elapsed=0
printf 'Waiting up to %ds for SSH on %s port %s...\n' "$TIMEOUT" "$HOST" "$PORT"

while [ "$elapsed" -lt "$TIMEOUT" ]; do
    if ssh -o ConnectTimeout=2 -o BatchMode=yes -o StrictHostKeyChecking=no -p "$PORT" "$USER"@"$HOST" pwd >/dev/null 2>&1; then
        printf 'SSH on %s:%s is ready after %ds.\n' "$HOST" "$PORT" "$elapsed"
        exit 0
    fi
    sleep "$INTERVAL"
    elapsed=$((elapsed + INTERVAL))
done

printf 'ERROR: SSH on %s:%s not ready after %ds.\n' "$HOST" "$PORT" "$TIMEOUT" >&2
exit 1
