#!/bin/sh
# Wait until a Home Assistant instance is ready (responds to /api/).
# Usage: wait-for-ha.sh <url> [timeout_seconds]
#
# Exit 0 = HA ready, Exit 1 = timeout reached.

URL="${1:-http://localhost:8123}"
TIMEOUT="${2:-120}"

elapsed=0
printf 'Waiting for HA at %s (timeout %ss)...\n' "$URL" "$TIMEOUT"

while [ "$elapsed" -lt "$TIMEOUT" ]; do
    if curl -sf --max-time 3 "$URL/api/" -o /dev/null 2>/dev/null; then
        printf 'HA ready at %s (after %ss)\n' "$URL" "$elapsed"
        exit 0
    fi
    sleep 2
    elapsed=$((elapsed + 2))
done

printf 'Timeout: HA not ready at %s after %ss\n' "$URL" "$TIMEOUT" >&2
exit 1
