#!/bin/bash

# ============================================================================ #
# Copyright (c) 2022 - 2026 NVIDIA Corporation & Affiliates.                   #
# All rights reserved.                                                         #
# Copyright 2025 IQM Quantum Computers                                         #
#                                                                              #
# This source code and the accompanying materials are made available under     #
# the terms of the Apache License 2.0 which accompanies this distribution.     #
# ============================================================================ #

# Check if iqm-client is installed, otherwise mark the test as skipped
@Python_EXECUTABLE@ -c "import iqm.iqm_client" 2> /dev/null
if [ $? -ne 0 ]; then
    echo "iqm-client is not installed. It is required for testing IQM integration. Please install it using pip install iqm-client. Skipping IQM tests."
    exit 77
fi

checkServerConnection() {
  PYTHONPATH=@CMAKE_BINARY_DIR@/python @Python_EXECUTABLE@ - << EOF
import socket
try:
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect(("localhost", 62443))
    s.close()
except Exception:
    exit(1)
EOF
}

# Create fake auth tokens file
tmp_file=$(mktemp)
PYTHONPATH=@CMAKE_BINARY_DIR@/python @Python_EXECUTABLE@ @CMAKE_BINARY_DIR@/python/tests/utils/mock_qpu/iqm/mock_iqm_cortex_cli.py $tmp_file
# Launch the fake server
PYTHONPATH=@CMAKE_BINARY_DIR@/python @Python_EXECUTABLE@ @CMAKE_BINARY_DIR@/python/tests/utils/start_mock_qpu.py iqm &
# we'll need the process id to kill it
pid=$(echo "$!")
n=0
while ! checkServerConnection; do
  sleep 1
  n=$((n+1))
  if [ "$n" -eq "60" ]; then
    kill -INT $pid
    exit 99
  fi
done
# Run the tests
if [ a${IQM_SERVER_URL} = a ]; then
  IQM_TOKEN="good_access_token" IQM_TOKENS_FILE=$tmp_file ./$1
else
  ./$1
fi
# Did they fail?
testsPassed=$?
# kill the server
kill -INT $pid
# wait for the server to die
sleep 1
# remove the tmp tokens file
rm $tmp_file
# return success / failure
exit $testsPassed
