#!/bin/bash

. ./scripts/test-setup-sonobuoy

# ---

cluster-pre-hook() {
  # gen-certs

  mkdir -p $TEST_DIR/db/$LABEL_SUFFIX/metadata
  local testID=$(basename $TEST_DIR)
  local name=$(echo $LABEL_SUFFIX-$testID | tee $TEST_DIR/db/$LABEL_SUFFIX/metadata/name)
  local port=$(timeout --foreground 5s bash -c get-port | tee $TEST_DIR/db/$LABEL_SUFFIX/metadata/port)
  local secret=$(echo "${RANDOM}${RANDOM}${RANDOM}" | tee $TEST_DIR/db/$LABEL_SUFFIX/metadata/secret)

  docker run --name $name \
    --privileged \
    -p 0.0.0.0:$port:5432 \
    -v $TEST_DIR/db-ca/:/db-ca \
    -e POSTGRES_USER=root \
    -e POSTGRES_PASSWORD=$secret \
    -d postgres:latest \
    >/dev/null
      # -c ssl=on \
      # -c ssl_ca_file=/db-ca/certs/ca.crt \
      # -c ssl_cert_file=/db-ca/certs/db.crt \
      # -c ssl_key_file=/db-ca/private/db.key \

  local ip=$(docker inspect --format '{{ .NetworkSettings.IPAddress }}' $name | tee $TEST_DIR/db/$LABEL_SUFFIX/metadata/ip)
  # local host=host.docker.internal
  local host=172.17.0.1

  DB_CONNECTION_TEST="
    docker run
      -v $TEST_DIR/db-ca/:/db-ca
      -e PGPASSWORD=$secret
      --rm postgres
      psql
        -h $host
        -p $port
        -U root
        -c \conninfo" \
    timeout --foreground 1m bash -c "wait-for-db-connection"
        # --set sslrootcert=/db-ca/certs/ca.crt
        # --set sslcert=/db-ca/certs/client.crt
        # --set sslkey=/db-ca/private/client.key

  echo "Started $LABEL_SUFFIX db @ $host"
  export SERVER_ARGS="${SERVER_ARGS}
    --datastore-endpoint=postgres://root:$secret@$host:$port/testdb?sslmode=disable
  "
    # --datastore-cafile /db-ca/certs/ca.crt
    # --datastore-certfile /db-ca/certs/client.crt
    # --datastore-keyfile /db-ca/private/client.key
}
export -f cluster-pre-hook

test-post-hook() {
  if [[ $1 -eq 0 ]]; then
    return
  fi
  local failures=$(awk '/^Summarizing .* Failures?:$/,0' "$TEST_DIR"/sonobuoy/plugins/e2e/results/global/e2e.log)
  # Ignore sonobuoy failures if only these flaky tests have failed
  local flakyTest1='[Fail] [sig-node] Probing container [It] should have monotonically increasing restart count [NodeConformance] [Conformance]'
  local flakyTest2='[Fail] [sig-node] Pods [It] should delete a collection of pods [Conformance]'
  local flakyTest3='[Fail] [sig-node] Pods [It] should run through the lifecycle of Pods and PodStatus [Conformance]' 
  local flakyTest4='[Fail] [sig-network] Proxy version v1 [It] A set of valid responses are returned for both pod and service ProxyWithPath [Conformance]'
  flakyFails=$( grep -scF -e "$flakyTest1" -e "$flakyTest2" -e "$flakyTest3" -e "$flakyTest4" <<< "$failures" )
  totalFails=$( grep -scF -e "[Fail]" <<< "$failures" )
  [ "$totalFails" -le "$flakyFails" ]
}
export -f test-post-hook