#!/bin/bash

display_usage() {
  echo -e "Usage:\n\t$0 <version> \n\nExample:\n\t$0 45"
}

if [ -z "${HOST}" ]; then
  export HOST=127.0.0.1
fi

if [ -z "${WORDPRESS_VERSION}" ]; then
  if [ $# -eq 0 ]; then
    display_usage
    exit 1
  fi
  
  wp_version_input="$1"
  php_version_input="$2"

  ## PHP Version ex "80"
  export PHP_VERSION="${php_version_input}"

  ## PHP Version ex "80"
  export PHP_VERSION_FULL="${PHP_VERSION:0:1}.${PHP_VERSION:1}"

  ## WordPress version ex "67"
  export WORDPRESS_VERSION="${wp_version_input}"

  ## WordPress version ex. "6.7"
  export WORDPRESS_VERSION_FULL="${WORDPRESS_VERSION:0:1}.${WORDPRESS_VERSION:1}"
fi

export MYSQL_PWD=root
export WORDPRESS_DATABASE=wordpress_${WORDPRESS_VERSION}
export WORDPRESS_PORT=80${WORDPRESS_VERSION}
export WORDPRESS_URL=http://wordpress
export WP_ENV_TESTS_PORT=80${WORDPRESS_VERSION}
export WP_ENV_CORE=WordPress/Wordpress#${WORDPRESS_VERSION_FULL}
export WP_ENV_PHP_VERSION=${PHP_VERSION_FULL}
export MOCK_PORT=8100


function wait_for_service_port {
  while ! curl -s localhost:$1 > /dev/null; do
    sleep 0.25
  done
}

function prepare_test_config {
  mv src/vendor/tinify/Tinify/Client.php src/vendor/tinify/Tinify/Client.php.bak
  cp test/fixtures/Client.php src/vendor/tinify/Tinify/Client.php

  mv src/config/class-tiny-config.php src/config/class-tiny-config.php.bak
  cp test/fixtures/class-tiny-config.php src/config/class-tiny-config.php
}

function restore_config {
  mv src/vendor/tinify/Tinify/Client.php.bak src/vendor/tinify/Tinify/Client.php
  mv src/config/class-tiny-config.php.bak src/config/class-tiny-config.php
}

function start_services {
  echo "Starting Mocks.."
  docker compose -f config/mocks.docker-compose.yml up -d

  echo "Starting WordPress.."
  npx wp-env start

  echo "Installing compatible plugins.."
  npx wp-env run tests-cli wp plugin install amazon-s3-and-cloudfront
}

function stop_services {
  docker compose -f config/mocks.docker-compose.yml down

  npx wp-env stop
}

function wait_for_services {
  echo "Waiting for WordPress..."
  wait_for_service_port 80${WORDPRESS_VERSION}
}

function setup {
  prepare_test_config
  start_services
  wait_for_services
  npm run test:playwright
}

function teardown {
  restore_config
  if ! [ "${KEEP_ALIVE}" ]; then
    stop_services
  fi
}

trap teardown EXIT
setup

