#!/bin/bash
# Run the Linux suite in a container against a real secret-service (gnome-keyring).
# Mirrors the 'cargo:test:linux' CI job so the two recipes can't drift.
set -euo pipefail
SCRIPTDIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"
cd "$SCRIPTDIR/.."

CONTAINER=${CONTAINER:-$(command -v podman || command -v docker || true)}
if [ -z "$CONTAINER" ]; then
    echo "no container runtime found: install podman or docker" >&2
    exit 1
fi
IMAGE=${IMAGE:-docker.io/library/rust:latest}

# The host target/ holds artifacts for a different triple; give the container its own.
exec "$CONTAINER" run --rm \
    -v "$PWD:/src" -w /src \
    -e CARGO_TARGET_DIR=/tmp/target \
    "$IMAGE" bash -euo pipefail -c '
        apt-get update -qq
        apt-get install -y --no-install-recommends dbus dbus-x11 gnome-keyring >/dev/null

        export XDG_RUNTIME_DIR=/tmp/xdg-runtime
        export XDG_DATA_HOME=/tmp/xdg-data
        export XDG_CONFIG_HOME=/tmp/xdg-config
        export XDG_CACHE_HOME=/tmp/xdg-cache
        mkdir -p "$XDG_RUNTIME_DIR" "$XDG_DATA_HOME" "$XDG_CONFIG_HOME" "$XDG_CACHE_HOME"
        chmod 700 "$XDG_RUNTIME_DIR"

        # dbus-secret-service talks over DBUS_SESSION_BUS_ADDRESS, which dbus-run-session sets up.
        # Unlock (and thereby create) the login keyring with an empty password.
        dbus-run-session -- bash -c "
            printf \"\n\" | gnome-keyring-daemon --unlock >/dev/null
            cargo test -- --test-threads=1
        "
    ' "$@"
