#!/bin/sh
# script/docker-smoke: build the Docker image, start it, and wait up to
# 30 seconds for its HEALTHCHECK to report healthy. Needs a Docker
# daemon, so it is not part of script/check; the Gitea workflow runs it
# after script/cibuild.
set -eu

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd -P)"
ROOT="$(cd "$SCRIPT_DIR/.." && pwd -P)"

main() {
    cd "$ROOT"
    "$SCRIPT_DIR/docker"

    # A fresh random key: the container publishes no port and is
    # removed on exit.
    key="$(head -c 32 /dev/urandom | base64)"

    # Docker 25 and later probe every 5 seconds during the image's
    # 10-second start period. --health-interval=1s makes it probe every
    # second after that instead of every 30, so a slow start still shows
    # as healthy within the 30-second wait.
    cid="$(docker create --health-interval=1s \
        -e PIXA_SIGNING_KEY="$key" "$("$SCRIPT_DIR/projectname")")"
    # Remove the container on any exit; turning signals into exit makes
    # an interrupted run clean up too.
    trap 'docker rm -f "$cid" >/dev/null' EXIT
    trap 'exit 1' HUP INT TERM
    docker start "$cid" >/dev/null

    deadline=$(($(date +%s) + 30))
    while [ "$(date +%s)" -lt "$deadline" ]; do
        health="$(docker inspect --format '{{.State.Health.Status}}' "$cid")"
        if [ "$health" = healthy ]; then
            echo "docker-smoke: container is healthy"
            return 0
        fi
        sleep 1
    done

    echo "docker-smoke: container not healthy after 30 seconds; its log:" >&2
    docker logs "$cid" >&2
    return 1
}

main "$@"
