#!/bin/bash
set -a
# Function to set variable only if not already set
set_if_unset() {
    local var_name="$1"
    local var_value="$2"
    [[ -z "${!var_name:-}" ]] && export "$var_name"="$var_value"
}

# Function to load env file
load_env_file() {
    local file="$1"
    [[ -f "$file" ]] || return 0

    while IFS='=' read -r key value || [[ -n "$key" ]]; do
        # Skip comments and empty lines
        [[ "$key" =~ ^[[:space:]]*# || -z "$key" ]] && continue

        # Trim whitespace
        key=$(echo "$key" | xargs)
        value=$(echo "$value" | xargs)

        [[ -n "$key" ]] && set_if_unset "$key" "$value"
    done < "$file"
}

# Load defaults, then overrides
load_env_file ".env.defaults"
load_env_file ".env"
set +a

if [ "$DRUPAL_TEST_WEBDRIVER_AUTOSTART" == "true" ]; then
  pkill -f "$DRUPAL_TEST_WEBDRIVER_BINARY"
fi

set -e

if [ "$DRUPAL_TEST_WEBDRIVER_AUTOSTART" == "true" ]; then
  eval "$DRUPAL_TEST_WEBDRIVER_BINARY $DRUPAL_TEST_WEBDRIVER_BINARY_FLAGS" &
  WEBDRIVER_BINARY_PID=$!
  sleep 2
  if ! kill -0 $WEBDRIVER_BINARY_PID 2>/dev/null; then
    echo "Error: $DRUPAL_TEST_WEBDRIVER_BINARY failed to start"
    exit 1
  fi
fi

if [ -z "$DRUPAL_TEST_WEBSERVER_USER" ]; then
  composer run _phpunit
else
  sudo -E -u "$DRUPAL_TEST_WEBSERVER_USER" composer run _phpunit
fi

if [ "$DRUPAL_TEST_WEBDRIVER_AUTOSTART" == "true" ]; then
  kill "$WEBDRIVER_BINARY_PID"
fi
