#!/bin/bash
set -e -x
cd $(dirname $0)/..

. ./scripts/version.sh
. ./tests/docker/test-helpers

# sysctl commands
sysctl -w fs.inotify.max_queued_events=16384
sysctl -w fs.inotify.max_user_instances=8192
sysctl -w fs.inotify.max_user_watches=524288
sysctl -w user.max_inotify_instances=8192
sysctl -w user.max_inotify_watches=524288

artifacts=$(pwd)/dist/artifacts
mkdir -p $artifacts

# ---

docker ps

export K3S_IMAGE="rancher/k3s:${VERSION_TAG}${SUFFIX}"
export VERSION_K8S # used by the sonobuoy tests subprocess
# ---
# Only run PR tests on arm arch, we use GitHub Actions for amd64 and arm64
# Run all tests on tag events, as we want test failures to block the release
if [ "$ARCH" == 'arm' ]; then

  go test ./tests/docker/basics/basics_test.go -k3sImage="$K3S_IMAGE" -ci
  echo "Did go test basics $?"

  # Extract v1.XX minor version for skew and upgrade tests
  minor_version=$(echo $VERSION_K8S | cut -d '.' -f1,2)

  go test ./tests/docker/cacerts/cacerts_test.go -k3sImage="$K3S_IMAGE" -ci
  echo "Did go test cacerts $?"

  go test ./tests/docker/skew/skew_test.go -k3sImage="$K3S_IMAGE" -channel="$minor_version" -ci
  echo "Did go test skew $?"

  go test ./tests/docker/bootstraptoken/bootstraptoken_test.go -k3sImage="$K3S_IMAGE" -ci
  echo "Did go test bootstraptoken $?"

  go test ./tests/docker/upgrade/upgrade_test.go -k3sImage="$K3S_IMAGE" -channel="$minor_version" -ci
  echo "Did go test upgrade $?"
  
  go test ./tests/docker/lazypull/lazypull_test.go -k3sImage="$K3S_IMAGE" -ci
  echo "Did go test lazypull $?"

fi


# ---

[ "$ARCH" != 'amd64' ] && \
  early-exit "Skipping remaining tests, images not available for $ARCH."

# ---

# Wait until all tests have finished
delay=15
(
set +x
while [ $(count-running-tests) -ge 1 ]; do
    sleep $delay
done
)

exit 0
