#!/bin/bash
# On amd64/i386 the package installs one binary per SIMD ISA and /usr/bin/vg is
# only a dispatcher that picks the best one the CPU can run.  Running
# "vg test" therefore exercises a single variant.  Test every installed
# variant explicitly so a regression in one of the other binaries is caught
# (Debian bug #987184).
set -u
shopt -s nullglob

# vg 1.78.0 predates the new snarl decomposition interface in libbdsg
# (https://github.com/vgteam/libbdsg/pull/247), which Debian's libbdsg already
# provides.  Six test cases still assert the old root/chain traversal
# behaviour; upstream adapts them in
# https://github.com/vgteam/vg/pull/5057, which is not part of 1.78.0.
# Remove these exclusions when packaging a vg release containing that work.
exclusions=(
    "~Snarl decomposition can deal with multiple connected components"
    "~Snarl decomposition can allow traversal of a simple net graph"
    "~Distance index's snarl functions return expected answers"
    "~Distance index can deal with chains that loop at the root"
    "~Distance index can deal with edges in the root"
    "~top level chain subgraph"
)

# CPU feature each variant needs, spelled as in /proc/cpuinfo.
declare -A cpu_need=(
    [plain]=""
    [sse]="sse"
    [sse2]="sse2"
    [sse3]="pni"
    [ssse3]="ssse3"
    [sse4.1]="sse4_1"
    [avx]="avx"
    [avx2]="avx2"
)

cpuflags=" $(sed -n 's/^flags[[:space:]]*:[[:space:]]*//p' /proc/cpuinfo 2>/dev/null \
    | head -n1 | tr 'A-Z' 'a-z') "

status=0
variants=(/usr/lib/vg/vg-*)
# Non-x86 architectures install the binary directly.
[ ${#variants[@]} -eq 0 ] && variants=(/usr/bin/vg)

for bin in "${variants[@]}"; do
    [ -x "$bin" ] || continue
    isa=${bin##*/vg-}
    [ "$bin" = /usr/bin/vg ] && isa=plain
    need=${cpu_need[$isa]-}
    if [ -n "$need" ] && [[ "$cpuflags" != *" $need "* ]]; then
        echo "SKIP: $(basename "$bin") (CPU lacks $need)"
        continue
    fi
    echo "RUN: $(basename "$bin")"
    if ! "$bin" test "${exclusions[@]}"; then
        echo "FAIL: $(basename "$bin")" >&2
        status=1
    fi
done

# /usr/bin/vg is normally the dispatcher; make sure it can still start.
if [ -L /usr/bin/vg ]; then
    echo "RUN: dispatcher /usr/bin/vg"
    /usr/bin/vg version || { echo "FAIL: dispatcher" >&2; status=1; }
fi

exit "$status"
