#!/bin/sh
# systemctl start no termina hasta comprobar el healthcheck del contenedor.
set -eu

DOCKER_BIN=${FILMOS_HERMES_DOCKER_BIN:-/usr/bin/docker}
CONTAINER=${FILMOS_HERMES_CONTAINER:-filmos-hermes}
TIMEOUT=${FILMOS_HERMES_HEALTH_TIMEOUT:-180}

case "$TIMEOUT" in
    ''|*[!0-9]*) echo "timeout de salud inválido: $TIMEOUT" >&2; exit 2 ;;
esac
[ "$TIMEOUT" -gt 0 ] || { echo "el timeout de salud debe ser positivo" >&2; exit 2; }

deadline=$(( $(date +%s) + TIMEOUT ))
while [ "$(date +%s)" -lt "$deadline" ]; do
    status=$("$DOCKER_BIN" inspect \
        --format '{{if .State.Health}}{{.State.Health.Status}}{{else}}{{.State.Status}}{{end}}' \
        "$CONTAINER" 2>/dev/null || true)
    case "$status" in
        healthy)
            echo "filmos-hermes: contenedor saludable"
            exit 0
            ;;
        unhealthy|exited|dead)
            echo "filmos-hermes: estado no saludable: $status" >&2
            exit 1
            ;;
        ''|created|restarting|running|starting) ;;
        *) echo "filmos-hermes: estado desconocido: $status" >&2; exit 1 ;;
    esac
    sleep 2
done

echo "filmos-hermes: el healthcheck no llegó a healthy en ${TIMEOUT}s" >&2
exit 1
