#!/bin/bash
# Run fluxion and check that every dependency it verifies at startup is
# reported as OK.
#
# Fluxion needs a display (it uses xterm), so it is run under Xvfb. Its stdin
# is kept open so that, after the dependency check, it blocks on the first
# menu (language selection) instead of looping on EOF. It is then stopped
# with SIGHUP, which triggers its normal cleanup routine (SIGINT can't be
# used: it is ignored by background jobs).

set -u

TIMEOUT=120
WORKDIR="${AUTOPKGTEST_TMP:-$(mktemp -d)}"
LOG="$WORKDIR/fluxion.log"

# Keep stdin open without ever sending data.
exec 3< <(exec sleep infinity)
sleeper=$!

# Fluxion writes to /dev/stdout, which would truncate a regular file, so its
# output goes through a pipe.
TERM=xterm xvfb-run -a fluxion <&3 > >(cat >"$LOG") 2>&1 &
pid=$!

strip_ansi() {
    sed 's/\x1b\[[0-9;?]*[a-zA-Z]//g' "$LOG" | tr -d '\0'
}

finished=0
for _ in $(seq "$TIMEOUT"); do
    if strip_ansi | grep -q "Select your language\|Missing dependencies"; then
        finished=1
        break
    fi
    kill -0 "$pid" 2>/dev/null || break
    sleep 1
done

# Stop fluxion and wait for xvfb-run to finish.
pkill -HUP -P "$pid" -f fluxion.sh || true
for _ in $(seq 30); do
    kill -0 "$pid" 2>/dev/null || break
    sleep 1
done
kill "$pid" 2>/dev/null || true
wait "$pid" 2>/dev/null || true
exec 3<&-
kill "$sleeper" 2>/dev/null || true
sleep 1 # let cat flush the log

output=$(strip_ansi)
checks=$(grep -E '^\s*\[\*\] \S+\.+ (OK\.|Missing!)' <<<"$output" || true)

echo "Dependency checks reported by fluxion:"
echo "$checks"
echo

if [ "$finished" -ne 1 ] || [ -z "$checks" ]; then
    echo "FAIL: fluxion did not reach the end of its dependency check" >&2
    echo "----- fluxion output -----" >&2
    echo "$output" >&2
    exit 1
fi

if grep -q "Missing!" <<<"$checks"; then
    echo "FAIL: missing dependencies:" >&2
    grep "Missing!" <<<"$checks" >&2
    exit 1
fi

echo "PASS: $(wc -l <<<"$checks") dependency checks OK"
