#!/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.

# Smoke test: run a minimal recipe through debos inside fakemachine.
# Based on fakemachine's run-command autopkgtest.

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=120s
else
    backend=qemu
    timeout=900s
fi
echo "# using $backend backend"

cat > smoke.yaml <<'EOF'
architecture: {{ .architecture }}

actions:
  - action: run
    description: Write a greeting
    command: echo "Hello from debos" > "${ARTIFACTDIR}/greeting.txt"
EOF

mkdir -p artifacts

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" \
        debos --fakemachine-backend="$backend" \
            --memory=512MB \
            --artifactdir=artifacts \
            -t architecture:"$(dpkg --print-architecture)" \
            smoke.yaml </dev/null 2>&1 | \
        sed -u -e 's/\x1bP[^\x1b]*\x1b\\//g' | \
        stdbuf -oL tr -d '\033\015' | \
        tee debos.log >&2; then
    e=0
else
    e=$?
fi

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

if grep -E "Recipe done" debos.log >&2; then
    echo "ok 2 - debos completed the recipe"
else
    echo "not ok 2 - debos did not complete the recipe"
    fail=1
fi

if grep -Fx "Hello from debos" artifacts/greeting.txt >&2; then
    echo "ok 3 - artifact was written from inside fakemachine"
else
    echo "not ok 3 - artifact missing or has unexpected content"
    fail=1
fi

exit "$fail"
