#!/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:-"${AUTOPKGTEST_TMP}"}"

if ! [ -w /dev/kvm ]; then
    echo "1..0 # SKIP no write access to /dev/kvm"
    exit 0
fi

if ! grep -E '^flags[[:space:]]*:.*[[:space:]](vmx|svm)( |$)' /proc/cpuinfo >&2; then
    echo "1..0 # SKIP could not find AMD-V (svm) or Intel VT-x (vmx) in /proc/cpuinfo"
    exit 0
fi

echo "1..3"
fail=0

# Filter out Esc and Tab for a cleaner log and easier grepping
if timeout -k 5s -s ABRT 60s \
        fakemachine env LC_ALL=C hello </dev/null 2>&1 | \
        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$' 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"
