#!/bin/sh

set -eu

component="${1:?usage: rekono-wait <postgres|valkey|backend|frontend|nginx>}"

case "${component}" in
    postgres) budget=35; description='PostgreSQL' ;;
    valkey)   budget=25; description='Valkey' ;;
    backend)  budget=80; description='Rekono backend' ;;
    frontend) budget=35; description='Rekono frontend' ;;
    nginx)    budget=35; description='Nginx' ;;
    *)        echo "unknown component: ${component}" >&2; exit 1 ;;
esac

check() {
    case "${component}" in
        postgres)
            pg_isready --quiet \
                --host "${RKN_DB_HOST:-/var/run/postgresql}" \
                --port "${RKN_DB_PORT:-5442}"
            ;;
        valkey)
            [ "$(valkey-cli -h "${RKN_RQ_HOST:-127.0.0.1}" \
                            -p "${RKN_RQ_PORT:-6479}" ping 2>/dev/null)" = 'PONG' ]
            ;;
        backend)
            curl --silent --fail --max-time 5 --output /dev/null \
                --unix-socket /run/rekono/backend/gunicorn.sock \
                http://localhost/api/schema/swagger-ui/
            ;;
        frontend)
            curl --silent --fail --max-time 5 --output /dev/null \
                http://127.0.0.1:3000
            ;;
        nginx)
            curl --silent --fail --insecure --max-time 5 --output /dev/null \
                "https://127.0.0.1:$(sed -n \
                    's/^[[:space:]]*listen[[:space:]]\+127\.0\.0\.1:\([0-9]\+\).*/\1/p' \
                    /etc/rekono/nginx.conf | head -n 1)"
            ;;
    esac
}

elapsed=0
while [ "${elapsed}" -lt "${budget}" ]; do
    if check; then
        exit 0
    fi
    elapsed=$((elapsed + 1))
    sleep 1
done

echo "Timed out after ${budget}s waiting for ${description} to become ready." >&2
exit 1
