#!/usr/bin/env bash
set -euo pipefail
source "$(dirname -- "${BASH_SOURCE[0]}")/engine.sh"
if "$ENGINE" container inspect "$CONTAINER" >/dev/null 2>&1; then
    "$ENGINE" start "$CONTAINER"
else
    actual=$("$ENGINE" image inspect --format '{{.Id}}' "$IMAGE")
    [[ "${actual#sha256:}" == dfd595e2afd48b8942a00ec61aef7d1f1c7929bb8b6bdb2c7b59f85f943e11e7 ]] || {
        echo 'Unexpected image identity; load the verified bundled archive first.' >&2
        exit 1
    }
    mkdir -p "$BASE/data"
    "$ENGINE" run -d --name "$CONTAINER" --pull=never --restart=unless-stopped \
        -p 127.0.0.1:3000:3000 -p 127.0.0.1:2222:22 \
        -v "$BASE/data:/data:Z" \
        -v "$BASE/bin:/opt/gitleaks/bin:ro,Z" \
        -v "$BASE/config:/opt/gitleaks/config:ro,Z" \
        -v "$BASE/hooks:/opt/gitleaks/hooks:ro,Z" \
        -v "$BASE/templates:/opt/gitleaks/templates:ro,Z" \
        -e USER_UID=1000 -e USER_GID=1000 \
        -e GIT_TEMPLATE_DIR=/opt/gitleaks/templates \
        -e GITEA__database__DB_TYPE=sqlite3 \
        -e GITEA__database__PATH=/data/gitea/gitea.db \
        -e GITEA__server__DOMAIN=localhost \
        -e GITEA__server__ROOT_URL=http://localhost:3000/ \
        -e GITEA__server__SSH_DOMAIN=localhost \
        -e GITEA__server__SSH_PORT=2222 \
        -e GITEA__security__INSTALL_LOCK=true \
        -e GITEA__security__DISABLE_GIT_HOOKS=true \
        -e GITEA__service__DISABLE_REGISTRATION=true \
        -e GITEA__server__OFFLINE_MODE=true \
        -e GITEA__picture__DISABLE_GRAVATAR=true \
        -e GITEA__picture__ENABLE_FEDERATED_AVATAR=false \
        -e GITEA__actions__ENABLED=false \
        "$IMAGE"
fi
for attempt in {1..60}; do
    if curl -fsS http://127.0.0.1:3000/api/healthz >/dev/null 2>&1; then
        echo 'Gitea ready at http://localhost:3000'
        exit 0
    fi
    sleep 1
done
echo 'Gitea did not become healthy; inspect container logs.' >&2
exit 1
