#!/usr/bin/env bash
# The lavapipe image: the CPU Vulkan ICD that CI's device-executing steps run on (the device tests,
# the conformance replay and public case qualification), and the lab's replica of CI with them.
# It is Arch Linux: the bootstrap tarball, and the packages of one Arch Linux Archive date, all
# named in ./pin. The tarball is checked against the pin's sha256, and every package against the
# signatures that the bootstrap's own keyring verifies.
#
#   lavapipe-image ensure
#       Build the pinned image unless it exists. Then print the pin, the packages the image holds
#       and its device's name and driver, and fail where any differs from the pin, or from the
#       venue line of crates/metal2vulkan-conformance/known-gaps-rt.tsv.
#   lavapipe-image run [--write DIR]... [--read PATH]... [--env NAME=VALUE]... -- COMMAND [ARG]...
#       Run COMMAND in the image, in the current directory, with no network and only the
#       environment named here. The checkout is mounted read-only at its own path, except each
#       DIR, which is writable; each PATH outside it is mounted read-only. The host's
#       cargo-nextest is mounted read-only, as the image's.
#   lavapipe-image nextest [--write DIR]... [--env NAME=VALUE]... ARCHIVE FILTERS [ARG]...
#       Run the tests of the nextest archive ARCHIVE that FILTERS holds (a filterset a line, as
#       only_in.py prints them) in the image, with LP_NUM_THREADS=1, each --env and --write as for
#       `run`, and nextest's ARGs.
#   lavapipe-image udmabuf
#       Say whether the containers get /dev/udmabuf, and exit 0 where they do.
#
# lavapipe exports a dma-buf through /dev/udmabuf, so the containers get the host's where it has
# one (LAVAPIPE_IMAGE_UDMABUF names another node; empty, none, as on a host without one). Where
# they get none, `nextest` skips the tests ./needs-udmabuf names, and `replay` the cases, each
# named in the log, since lavapipe there exports no dma-buf.
#
# Every download is `curl -A curl` of an exact URL on archive.archlinux.org: the tarball, and the
# date's package databases and packages, which pacman fetches through the same command
# (XferCommand). Downloads are kept under ~/.cache/m2v-lavapipe-image (CI caches that directory,
# keyed on ./pin), so a run whose pin has not moved downloads nothing. The fetched tree lives
# there and in the container runtime's own store, and never on the host build's path: the tests
# are built on the host and only run in the image. Linux x86-64 only; the container runtime is
# docker, else podman.
#
# Every container is held to the share of the job that runs it, since the container runtime runs
# it outside that job's processes: LAVAPIPE_IMAGE_MEMORY (docker's form, such as 24g) bounds its
# memory, swap included, else the host's memory does; CARGO_BUILD_JOBS bounds its CPUs, else the
# host's count does.
set -euo pipefail

here=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -P)
root=$(cd "$here/../.." && pwd -P)
ledger=$root/crates/metal2vulkan-conformance/known-gaps-rt.tsv
cache=$HOME/.cache/m2v-lavapipe-image

die() {
    echo "lavapipe-image: $*" >&2
    exit 1
}

# shellcheck source=pin
. "$here/pin"
[ -n "${date:-}" ] && [ -n "${bootstrap:-}" ] && [ -n "${bootstrap_sha256:-}" ] && [ -n "${packages:-}" ] ||
    die "$here/pin names no date, bootstrap, bootstrap_sha256 or packages"

if command -v docker >/dev/null; then
    runtime=docker
    as_user=(--user "$(id -u):$(id -g)")
elif command -v podman >/dev/null; then
    runtime=podman
    as_user=(--userns keep-id)
else
    die "neither docker nor podman is on PATH"
fi
udmabuf=${LAVAPIPE_IMAGE_UDMABUF-/dev/udmabuf}
memory=${LAVAPIPE_IMAGE_MEMORY:-$(sed -n 's/^MemTotal: *\([0-9]*\) kB$/\1k/p' /proc/meminfo)}
limits=(--memory "$memory" --memory-swap "$memory" --cpus "${CARGO_BUILD_JOBS:-$(nproc)}")

# The image's tag follows the pin and this script, so a change to either builds a new image.
tag=$(cat "$here/pin" "$here/lavapipe-image" "$here/bootstrap_root.py" | sha256sum | cut -c1-16)
image=m2v-lavapipe:$tag

# The upstream version of a package version: no epoch, no package release.
upstream() {
    local version=${1#*:}
    echo "${version%-*}"
}

# The pinned version of package $1.
pinned() {
    local entry
    for entry in $packages; do
        if [ "${entry%%=*}" = "$1" ]; then
            echo "${entry#*=}"
            return
        fi
    done
    die "$here/pin pins no $1"
}

build() {
    local tarball=$cache/${bootstrap##*/} sync=$cache/sync-$date names=() entry base container
    mkdir -p "$cache/pkg" "$sync"
    # The cache holds one pin's downloads: another date's tarball and databases go.
    find "$cache" -maxdepth 1 \( -name 'archlinux-bootstrap-*' ! -name "${tarball##*/}" ! -name "${tarball##*/}.part" \
        -o -name 'sync-*' ! -name "sync-$date" \) -exec rm -rf {} +
    if [ ! -s "$tarball" ] || [ "$(sha256sum <"$tarball" | cut -c1-64)" != "$bootstrap_sha256" ]; then
        rm -f "$tarball"
        curl -A curl -fL --retry 3 -C - -o "$tarball.part" "$bootstrap" ||
            die "fetching $bootstrap failed (curl exit $?): the archive was unreachable or too slow; nothing was tested"
        mv "$tarball.part" "$tarball"
    fi
    [ "$(sha256sum <"$tarball" | cut -c1-64)" = "$bootstrap_sha256" ] ||
        die "$tarball is not the pin's sha256 $bootstrap_sha256"
    cat >"$cache/pacman.conf" <<EOF
[options]
Architecture = auto
SigLevel = Required DatabaseOptional
LocalFileSigLevel = Optional
XferCommand = /usr/bin/curl -A curl -fL -C - -o %o %u

[core]
Server = https://archive.archlinux.org/repos/${date//-//}/\$repo/os/\$arch

[extra]
Server = https://archive.archlinux.org/repos/${date//-//}/\$repo/os/\$arch
EOF
    for entry in $packages; do names+=("${entry%%=*}"); done
    base=m2v-lavapipe-base:$tag
    container=m2v-lavapipe-build-$tag
    # What an interrupted build left: its container (stopped here) and its base image.
    "$runtime" ps -a --format '{{.Names}}' | sed -n '/^m2v-lavapipe-build-/p' | xargs -r "$runtime" rm -f >/dev/null || true
    "$runtime" images --format '{{.Repository}}:{{.Tag}}' | sed -n '/^m2v-lavapipe-base:/p' | xargs -r "$runtime" rmi >/dev/null 2>&1 || true
    zstd -dc "$tarball" | python3 -I "$here/bootstrap_root.py" | "$runtime" import - "$base" >/dev/null
    # The date's databases are fetched once (-y only where they are missing). The packages the
    # transaction needs are fetched eight at a time by the same curl command pacman runs, since the
    # archive serves each connection slowly at times, and pacman fetches whatever that missed.
    # Every package is checked against the bootstrap keyring's signatures; the cache keeps what the
    # image holds.
    "$runtime" run --name "$container" "${limits[@]}" \
        -v "$cache/pkg:/var/cache/pacman/pkg" -v "$sync:/var/lib/pacman/sync" \
        -v "$cache/pacman.conf:/etc/pacman.conf:ro" \
        "$base" bash -euc '
            owner=$1
            shift
            pacman-key --init >/dev/null 2>&1
            pacman-key --populate archlinux >/dev/null 2>&1
            if [ ! -s /var/lib/pacman/sync/core.db ] || [ ! -s /var/lib/pacman/sync/extra.db ]; then
                pacman -Sy
            fi
            pacman -Su --print --print-format %l --noconfirm --needed "$@" | sed -n "/^https:/p" |
                xargs -r -P 8 -n 1 bash -c '\''
                    f=/var/cache/pacman/pkg/${1##*/}
                    curl -A curl -fsSL --retry 3 -C - -o "$f.part" "$1" && mv "$f.part" "$f" || true
                '\'' fetch
            pacman -Su --noconfirm --needed "$@" || {
                echo "lavapipe-image: pacman could not fetch or install the pin'\''s packages from the archive; nothing was tested" >&2
                exit 1
            }
            yes | pacman -Sc >/dev/null
            chown -R "$owner" /var/cache/pacman/pkg /var/lib/pacman/sync
        ' bash "$(id -u):$(id -g)" "${names[@]}"
    "$runtime" commit "$container" "$image" >/dev/null
    "$runtime" rm "$container" >/dev/null
    "$runtime" rmi "$base" >/dev/null
    # One image is kept: an older pin's goes, unless a container still runs it.
    "$runtime" images --format '{{.Repository}}:{{.Tag}}' | sed -n "/^m2v-lavapipe:/{/:$tag\$/!p}" |
        xargs -r "$runtime" rmi >/dev/null 2>&1 || true
}

# Print what the image holds and its device, and fail on any difference from the pin or the
# ledger's venue line.
check() {
    local line re mesa llvm loader layers held name version device driver bad=0
    line=$(sed -n 's/^# llvmpipe: \(.*\)$/\1/p' "$ledger")
    re='^Mesa ([0-9.]+), LLVM ([0-9.]+), Vulkan loader ([0-9.]+), validation layers ([0-9.]+)\.'
    [[ $line =~ $re ]] ||
        die "$ledger has no line '# llvmpipe: Mesa M, LLVM L, Vulkan loader V, validation layers W.'"
    mesa=${BASH_REMATCH[1]} llvm=${BASH_REMATCH[2]} loader=${BASH_REMATCH[3]} layers=${BASH_REMATCH[4]}
    echo "lavapipe image $image: archive date $date, bootstrap ${bootstrap##*/} sha256 $bootstrap_sha256"
    echo "ledger venue llvmpipe: Mesa $mesa, LLVM $llvm, Vulkan loader $loader, validation layers $layers"
    # The image keeps no package database (the build mounted it), so pacman reads the local one.
    held=$("$runtime" run --rm --network none "${limits[@]}" "$image" pacman -Q 2>/dev/null)
    for name in "${names[@]}"; do
        version=$(sed -n "s/^$name //p" <<<"$held")
        echo "package $name ${version:-missing} (pin $(pinned "$name"))"
        [ "$version" = "$(pinned "$name")" ] || { echo "lavapipe-image: $name is ${version:-missing}, not the pin's" >&2; bad=1; }
    done
    [ "$(upstream "$(pinned vulkan-swrast)")" = "$mesa" ] || { echo "lavapipe-image: the pin's Mesa is not the ledger's $mesa" >&2; bad=1; }
    [ "$(upstream "$(pinned llvm-libs)")" = "$llvm" ] || { echo "lavapipe-image: the pin's LLVM is not the ledger's $llvm" >&2; bad=1; }
    [ "$(upstream "$(pinned vulkan-icd-loader)")" = "$loader" ] || { echo "lavapipe-image: the pin's loader is not the ledger's $loader" >&2; bad=1; }
    [ "$(upstream "$(pinned vulkan-validation-layers)")" = "$layers" ] || { echo "lavapipe-image: the pin's layers are not the ledger's $layers" >&2; bad=1; }
    device=$("$runtime" run --rm --network none "${limits[@]}" "$image" vulkaninfo --summary 2>/dev/null |
        sed -n 's/^[[:space:]]*\(deviceName\|driverInfo\)[[:space:]]*= //p')
    driver=$(sed -n 2p <<<"$device")
    device=$(sed -n 1p <<<"$device")
    echo "device: $device; driver: $driver"
    [[ $device == "llvmpipe (LLVM $llvm, "* ]] || { echo "lavapipe-image: the device is not llvmpipe of LLVM $llvm" >&2; bad=1; }
    # The upstream versions alone: a distribution's build adds its own suffix to Mesa's.
    re="^Mesa ${mesa//./\\.}([- ].*)? \\(LLVM ${llvm//./\\.}\\)\$"
    [[ $driver =~ $re ]] ||
        { echo "lavapipe-image: the driver is not Mesa $mesa with LLVM $llvm" >&2; bad=1; }
    [ $bad = 0 ] || die "the image differs from its pin or from the ledger's venue line"
}

names=()
for entry in $packages; do names+=("${entry%%=*}"); done

# Whether the containers get the host's udmabuf node: docker's daemon opens it for them; rootless
# podman only where this user may.
has_udmabuf() {
    [ -n "$udmabuf" ] && [ -c "$udmabuf" ] &&
        { [ $runtime = docker ] || { [ -r "$udmabuf" ] && [ -w "$udmabuf" ]; }; }
}

# Say whether the containers get the node, and answer it.
say_udmabuf() {
    if has_udmabuf; then
        echo "lavapipe-image: the containers get $udmabuf"
    else
        echo "lavapipe-image: the containers get no /dev/udmabuf (${udmabuf:-none named}), so lavapipe exports no dma-buf there"
        return 1
    fi
}

# The lines of ./needs-udmabuf whose first word is $1, that word removed.
needs_udmabuf() {
    sed -n "s/^$1 //p" "$here/needs-udmabuf"
}

run() {
    local mounts=(-v "$root:$root:ro") envs=() nextest
    while [ $# -gt 0 ]; do
        case $1 in
        --write)
            mounts+=(-v "$(cd "$2" && pwd -P):$(cd "$2" && pwd -P)")
            shift 2
            ;;
        --read)
            mounts+=(-v "$(realpath "$2"):$(realpath "$2"):ro")
            shift 2
            ;;
        --env)
            envs+=(-e "$2")
            shift 2
            ;;
        --)
            shift
            break
            ;;
        *) die "run: unknown option $1" ;;
        esac
    done
    [ $# -gt 0 ] || die "run: no command"
    "$runtime" image inspect "$image" >/dev/null 2>&1 || die "no image $image: run '$0 ensure' first"
    if nextest=$(command -v cargo-nextest); then
        mounts+=(-v "$(realpath "$nextest"):/usr/local/bin/cargo-nextest:ro")
    fi
    if has_udmabuf; then
        mounts+=(--device "$udmabuf:/dev/udmabuf")
        if [ $runtime = docker ]; then
            mounts+=(--group-add "$(stat -c %g "$udmabuf")")
        else
            mounts+=(--group-add keep-groups)
        fi
    fi
    "$runtime" run --rm --network none "${limits[@]}" "${as_user[@]}" "${mounts[@]}" -w "$(pwd -P)" \
        -e HOME=/tmp/home -e LANG=C.UTF-8 -e PATH=/usr/local/bin:/usr/bin "${envs[@]}" \
        "$image" bash -c 'mkdir -p "$HOME" && exec "$@"' bash "$@"
}

case ${1:-} in
ensure)
    if ! "$runtime" image inspect "$image" >/dev/null 2>&1; then
        build
    fi
    check
    say_udmabuf || true
    ;;
run)
    shift
    run "$@"
    ;;
udmabuf)
    say_udmabuf
    ;;
nextest)
    shift
    options=()
    while [ $# -gt 0 ]; do
        case $1 in
        --write | --env)
            [ $# -ge 2 ] || die "nextest: $1 needs a value"
            options+=("$1" "$2")
            shift 2
            ;;
        *) break ;;
        esac
    done
    [ $# -ge 2 ] || die "usage: $0 nextest [--write DIR]... [--env NAME=VALUE]... ARCHIVE FILTERS [ARG]..."
    archive=$(realpath "$1") filters=$(realpath "$2")
    shift 2
    if ! has_udmabuf; then
        kept=$(mktemp)
        trap 'rm -f "$kept"' EXIT
        cp "$filters" "$kept"
        while read -r binary test; do
            set_line="binary_id(=$binary) & test(=$test)"
            echo "lavapipe-image: skipped $binary $test: it needs a dma-buf export, and the containers get no /dev/udmabuf"
            grep -vxF "$set_line" "$kept" >"$kept.next" || true
            mv "$kept.next" "$kept"
        done < <(needs_udmabuf test)
        filters=$kept
    fi
    run --read "$archive" --read "$filters" --env LP_NUM_THREADS=1 ${options[@]+"${options[@]}"} -- bash -c '
        archive=$1 filters=$2 root=$3
        shift 3
        sets=()
        while IFS= read -r set; do sets+=(-E "$set"); done <"$filters"
        exec cargo-nextest nextest run --archive-file "$archive" --workspace-remap "$root" "$@" "${sets[@]}"
    ' bash "$archive" "$filters" "$root" "$@"
    ;;
replay)
    [ $# -eq 2 ] || die "usage: $0 replay CONFORMANCE"
    conformance=$2
    cases=()
    if ! has_udmabuf; then
        skipped=$(needs_udmabuf case)
        for name in $skipped; do
            echo "lavapipe-image: skipped case $name: it needs a dma-buf export, and the containers get no /dev/udmabuf"
        done
        while read -r name _; do
            [[ " $(echo $skipped) " == *" $name "* ]] || cases+=("$name")
        done < <("$conformance" cases)
    fi
    run --env LP_NUM_THREADS=1 -- "$conformance" replay --cpu "${cases[@]}"
    ;;
*)
    sed -n '2,/^set -euo/p' "$0" | sed '$d' >&2
    exit 64
    ;;
esac
