#!/bin/bash

# Copyright © 2018 Collabora Ltd.
#
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

set -e
set -u
set -o pipefail

cd "$AUTOPKGTEST_TMP"

kernel_found=false
for dir in /lib/modules/[0-9]*; do
    rel="${dir##*/}"
    if [ -e "$dir/vmlinuz" ] || [ -e "/boot/vmlinuz-$rel" ]; then
        kernel_found=true
    fi
done
if ! "$kernel_found"; then
    echo "1..0 # SKIP no kernel found"
    exit 77
fi

# Use KVM when available, otherwise fall back to (much slower) emulation
if [ -w /dev/kvm ]; then
    backend=kvm
    timeout=60s
else
    backend=qemu
    timeout=600s
fi
echo "# using $backend backend"

echo "1..3"
fail=0

# Filter out terminal queries (DCS sequences), Esc and CR for a cleaner
# log and easier grepping
if timeout -k 5s -s ABRT "$timeout" \
        fakemachine --backend="$backend" env LC_ALL=C hello </dev/null 2>&1 | \
        sed -u -e 's/\x1bP[^\x1b]*\x1b\\//g' | \
        stdbuf -oL tr -d '\033\015' | \
        tee fakemachine.log >&2; then
    e=0
else
    e=$?
fi

if [ "$e" -eq 0 ]; then
    echo "ok 1 - fakemachine hello exited successfully"
elif [ "$e" -eq 124 ]; then
    echo "not ok 1 - fakemachine hello timed out"
    fail=1
else
    echo "not ok 1 - fakemachine hello exited $e"
    fail=1
fi

if grep -E "^Running env LC_ALL=C hello using $backend backend$" fakemachine.log >&2; then
    echo "ok 2 - fakemachine tried to run hello"
else
    echo "not ok 2 - fakemachine didn't get as far as running hello"
    fail=1
fi

if grep -E '^Hello, world!$' fakemachine.log >&2; then
    echo "ok 3 - received a friendly greeting"
else
    echo "not ok 3 - did not receive a friendly greeting"
    fail=1
fi

exit "$fail"
