#!/usr/bin/env bash
set -euo pipefail

if [[ -f "tidb-operator-e2e-online.yaml" ]] ; then
  operator_yaml="tidb-operator-e2e-online.yaml"
else
  operator_yaml="${1:-""}"
  if ! [[ -f "$operator_yaml" ]]; then
    echo "No Operator YAML" >&2
    exit 1
  fi
fi

kubectl delete -f "$operator_yaml" --timeout 30s || true
kubectl create -f "$operator_yaml"
trap "kubectl delete -f $operator_yaml --timeout 30s" EXIT

elapseTime=0
period=5
threshold=300
while true
do
	sleep $period
	elapseTime=$(( elapseTime+$period ))
	kubectl get po/tidb-operator-e2e -n kube-system 2>/dev/null || continue
	kubectl get po/tidb-operator-e2e -n kube-system|grep Running && break || true
	if [[ $elapseTime -gt $threshold ]]
	then
		echo "wait e2e pod timeout, elapseTime: $elapseTime"
		exit 1
	fi
done

execType=0
while true
do
	if [[ $execType -eq 0 ]]
	then
		kubectl logs -f tidb-operator-e2e -n kube-system|tee -a result.log
	else
		execType=0
		kubectl logs --tail 1 -f tidb-operator-e2e -n kube-system|tee -a result.log
	fi
	## verify that the log output is exit normally
	tail -5 result.log|egrep 'Test Suite Failed|Test Suite Passed'||execType=$?
	[[ $execType -eq 0 ]] && break
done

ret=0
tail -1 result.log | grep 'Test Suite Passed' || ret=$?
rm result.log
exit $ret
