#!/bin/bash

set -e

MYDIR=$(dirname $0)

. "$MYDIR"/tests/framework

SNAPPY=snappy

if [ "$1" != "--yes-really" ]; then
    echo "The selftest may be destructive, please run with:"
    echo "   --yes-really"
    echo "if you know what you are doing"
    exit 1
fi

. "$MYDIR"/tests/settings

. "$MYDIR"/tests/common.sh

# prepare the environment
if [ -z "$ADT_REBOOT_MARK" ]; then
    sudo systemctl stop snappy-autopilot.timer
    sudo snappy remove "$framework" 2>&1 || true
    sudo snappy remove hello-world 2>&1 || true
    sudo snappy remove xkcd-webserver 2>&1 || true
fi

for test in "$MYDIR"/tests/*_test_*[!~#]; do
    CURRENT_TEST=$(basename $test)

    # after a reboot, skip ahead to the test that triggered it
    if [ -n "$ADT_REBOOT_MARK" ]; then
        if [ "$ADT_REBOOT_MARK" == "$CURRENT_TEST" ]; then
            echo "****** Resuming $test after reboot"
        else
            continue
        fi
    else
        echo "****** Running $test"
    fi

    . "$test"
    if ! (test 2>&1); then
        echo "FAILED: $test"
        exit 1
    fi

    # clear reboot marker
    unset ADT_REBOOT_MARK
done
