#!/usr/bin/env bash

# Copyright (c) 2019 Tigera, Inc. All rights reserved.
#
# 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

source .semaphore/new-kernel-common.sh

vm_name_prefix=$1
project=unique-caldron-775
zone=${ZONE:-europe-west3-c}
my_dir="$(dirname $0)"
repo_dir="."
artifacts_dir="$repo_dir/artifacts"

echo
echo "===== Starting tests ====="
echo

pids=()
monitor_pids=()
log_files=()
for batch in "${batches[@]}"; do
  vm_name="$vm_name_prefix$batch"
  log_file="$artifacts_dir/test-$batch.log"
  log_files+=( $log_file )
  if [ $batch = "ut" ]; then
    VM_NAME=$vm_name $my_dir/on-test-vm make --directory=calico/${REPO_NAME} ut-bpf check-wireguard >& "$log_file" &
    pid=$!
    pids+=( $pid )
  else
    VM_NAME=$vm_name ./.semaphore/on-test-vm make --directory=calico/${REPO_NAME} fv-bpf GINKGO_FOCUS=BPF-SAFE FV_NUM_BATCHES=8 FV_BATCHES_TO_RUN="$batch" >& "$log_file" &
    pid=$!
    pids+=( $pid )
  fi

  prefix="[batch=${batch} pid=${pid}]"
  echo "$prefix Started test batch in background; monitoring its log ($log_file)."
  (
    tail -F $log_file | grep --line-buffered \
      -e "Failure" \
      -e "SUCCESS" \
      -e "Parallel test node" \
      -e "Test batch" \
      -C10 | sed 's/.*/'"${prefix}"' &/';
  ) &
  mon_pid=$!
  monitor_pids+=( $mon_pid )
done

final_result=0

echo
echo "===== Waiting for background test runners to finish ===="
echo

num_batches=${#batches[@]}
summary=()
for (( i=0; i<num_batches; i++ )); do
  batch=${batches[$i]}
  pid=${pids[$i]}
  echo "Waiting for test batch $batch to finish (PID=$pid)..."
  if wait "$pid"; then
    summary+=( "Test batch $batch SUCCEEDED" )
    echo "===== Test batch $batch SUCCEEDED (PID=$pid).  Log file will be uploaded as artifact ${log_files[$i]}. ====="
  else
    summary+=( "Test batch $batch FAILED; Log file will be uploaded as artifact ${log_files[$i]}" )
    echo "===== Test batch $batch FAILED (PID=$pid).  Log file will be uploaded as artifact ${log_files[$i]}. ====="
    final_result=1
  fi
done

echo
echo "===== Shutting down test monitors ====="
for pid in "${monitor_pids[@]}"; do
  kill $pid || true
done

echo "===== Results summary ====="
for s in "${summary[@]}"; do
  echo "  $s"
done
echo
echo "===== Done, exiting with RC=$final_result ====="

exit $final_result
