#!/bin/bash
#
# Test script for the LTS/KCS server

NO_ACTION=

d=$(dirname "$0")
if test $d = "." ; then
    DIR=$(dirname $(pwd))
else
    DIR=$(realpath $(dirname $(dirname "$0")))
fi

. "$DIR/selftests/config"
if test -f $DIR/selftests/config.custom ; then
    . "$DIR/selftests/config.custom"
fi
. "$DIR/selftests/util/setup"
. "$DIR/selftests/util/ltm"

GCE_XFSTESTS="$DIR/run-fstests/gce-xfstests"
DATECODE="$(date +%Y%m%d%H%M)"
GCE_TEST_VMS=

while [ "$1" != "" ]; do
    case $1 in
	--no-action)
	    NO_ACTION=echo
	    ;;
    esac
    shift
done

if ! shutdown_ltm; then
    exit 1
fi

LTM_TEST_FILE=/tmp/ltm_test

cp /dev/null $LTM_TEST_FILE
GS_BUCKET=$(gce-xfstests get-bucket)

function test-ltm ()
{
    ARCH=$1
    KERNEL_DEB=$2

    if test -f "$KERNEL_DEB" ; then
	if test -n "$NO_ACTION" ; then
	    $NO_ACTION $GCE_XFSTESTS upload-kernel --kernel $KERNEL_DEB \
		       kernel-$ARCH.deb
	fi
	$GCE_XFSTESTS upload-kernel --kernel $KERNEL_DEB kernel-$ARCH.deb
	k=$"$GS_BUCKET/kernel-$ARCH.deb"
	a=
	if test $ARCH = "arm64" ; then
	    a="--arch $ARCH"
	fi
	echo "gce-xfstests ltm -c ext4/4k,btrfs/4k generic/001 btrfs/001 " \
	     --testrunid "test-$DATECODE-$ARCH"	--no-email --no-junit-email \
	     "btrfs/064 $a --kernel $k" >> $LTM_TEST_FILE
	GCE_TEST_VMS="$GCE_TEST_VMS ltm-test-$DATECODE-$ARCH"
    fi
}

function test-kcs ()
{
    ARCH=$1

    a=
    if test $ARCH = "arm64" ; then
	a="--arch $ARCH"
    fi
    echo "gce-xfstests ltm -c ext4/4k,btrfs/4k generic/001 btrfs/001 btrfs/064 $a " \
	 "--repo https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git " \
	 "--no-email --no-junit-email --commit v5.15.79 " \
	 "--testrunid testkcs-$DATECODE-$ARCH" \
	 >> $LTM_TEST_FILE
	GCE_TEST_VMS="$GCE_TEST_VMS ltm-testkcs-$DATECODE-$ARCH"
}

test-kcs amd64
test-kcs arm64
test-ltm amd64 $DIR/selftests/kernels/kernel-amd64.deb
test-ltm arm64 $DIR/selftests/kernels/kernel-arm64.deb

if test -n "$NO_ACTION" ; then
   echo "ltm-test script:"
   cat $LTM_TEST_FILE
   echo ""
fi

GS_PREFIX="$(gce-xfstests get-bucket)"

$NO_ACTION gsutil cp $LTM_TEST_FILE $GS_PREFIX/ltm-batch/ltm-test
rm -f $LTM_TEST_FILE
$NO_ACTION $GCE_XFSTESTS launch-ltm --skip-rc

echo "Datecode: $DATECODE"
echo -n "Waiting for test results..."
w=60
while /bin/true
do
    n=$($GCE_XFSTESTS ls-results | grep "$DATECODE" | grep .tar.xz | \
	    grep -v "64-a[ab]" | wc -l)
    echo -n "$n"
    sleep "$w"
    if test "$n" -eq 1 ; then
	w=30
    elif test "$n" -ge 2 ; then
	w=15
    fi
    if test "$n" -ge 4 ; then
	break
	echo " "
    fi
done

for i in $GCE_TEST_VMS ; do
    echo -n "Checking test VM $i: "
    totals=$($GCE_XFSTESTS get-results "$i" | grep "^Totals: ")
    n=$(echo "$totals" | wc -l)
    t=$(echo "$totals" | grep -v "[13] tests")
    if test "$n" -eq 2 -a -z "$t" ; then
        echo "Passed"
	$GCE_XFSTESTS rm-results "$i" >& /dev/null
    else
	echo "FAILED!"
	echo "   Test results available via: gce-xfstests get-results $i"
    fi
done
