#!/usr/bin/env bash

if [ $# -lt 2 ]; then
	echo "usage: $0 <db-user> <db-pass>"
	exit 1
fi

DB_USER=$1
DB_PASS=$2
WP_TESTS_TAG="tags/4.9.7"

# Get temp directory
TMPDIR=${TMPDIR-/tmp}
TMPDIR=$(echo $TMPDIR | sed -e "s/\/$//")

# Evaluate current directory
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

# Evaluate application root directory
WEB_ROOT_DIR="$( dirname "$( dirname "$( dirname "$( dirname "$( dirname "$DIR" )" )" )" )" )"
WP_CORE_DIR="$WEB_ROOT_DIR"/wp

# Location where wordpress testing suite will be installed
WP_TESTS_DIR=${WP_TESTS_DIR-$TMPDIR/wordpress-tests-lib}
WP_TEST_APPLICATION_DIR=${WP_TEST_APPLICATION_DIR-$TMPDIR/wiaas-backend-test}

download() {
    if [ `which curl` ]; then
        curl -s "$1" > "$2";
    elif [ `which wget` ]; then
        wget -nv -O "$2" "$1"
    fi
}

set -ex

# Since test enviroment needs to start with fresh setup
# we will install application in /tmp/ folder and execute all migrations
setup_test_application() {
    rm -rf "$WP_TEST_APPLICATION_DIR"

    mkdir "$WP_TEST_APPLICATION_DIR"

    mkdir "$WP_TEST_APPLICATION_DIR"/app

    cp -r "$WEB_ROOT_DIR/app/mu-plugins" "$WP_TEST_APPLICATION_DIR/app/mu-plugins"

    mkdir "$WP_TEST_APPLICATION_DIR"/app/plugins
    cp -r  "$WEB_ROOT_DIR"/app/plugins/wiaas  "$WP_TEST_APPLICATION_DIR"/app/plugins/wiaas

    cp -r  "$WEB_ROOT_DIR"/app/plugins/gravityflow  "$WP_TEST_APPLICATION_DIR"/app/plugins/gravityflow
    cp -r  "$WEB_ROOT_DIR"/app/plugins/gravityforms  "$WP_TEST_APPLICATION_DIR"/app/plugins/gravityforms

    mkdir "$WP_TEST_APPLICATION_DIR"/app/themes

    mkdir "$WP_TEST_APPLICATION_DIR"/app/uploads

    cp -r  "$WEB_ROOT_DIR"/config  "$WP_TEST_APPLICATION_DIR"/config
    sed -i "s|define('WP_ENV', env('WP_ENV') ?: 'development');|define('WP_ENV', 'test');|" "$WP_TEST_APPLICATION_DIR"/config/application.php

    cp "$WEB_ROOT_DIR/composer.json" "$WP_TEST_APPLICATION_DIR/composer.json"
    cp "$WEB_ROOT_DIR/composer.lock" "$WP_TEST_APPLICATION_DIR/composer.lock"
    cp "$WEB_ROOT_DIR/index.php" "$WP_TEST_APPLICATION_DIR/index.php"
    cp "$WEB_ROOT_DIR/wp-config.php" "$WP_TEST_APPLICATION_DIR/wp-config.php"
    cp "$WEB_ROOT_DIR/wp-cli.yml" "$WP_TEST_APPLICATION_DIR/wp-cli.yml"

  {
    echo "MYSQL_DATABASE=wordpress_test"
    echo "MYSQL_USER=wp_admin_test"
    echo "MYSQL_PASSWORD=wp_admin_test_password"
    echo "WP_AUTH_KEY=test"
    echo "WP_SECURE_AUTH_KEY=test"
    echo "WP_LOGGED_IN_KEY=test"
    echo "WP_NONCE_KEY=test"
    echo "WP_AUTH_SALT=test"
    echo "WP_SECURE_AUTH_SALT=test"
    echo "WP_LOGGED_IN_SALT=test"
    echo "WP_NONCE_SALT=test"
    echo "WP_JWT_AUTH_SECRET_KEY=test"
  } >> "$WP_TEST_APPLICATION_DIR/.env"

}


install_test_suite() {
	# set up testing suite if it doesn't yet exist
	if [ ! -d $WP_TESTS_DIR ]; then
		# set up testing suite
		mkdir -p $WP_TESTS_DIR
		svn co --quiet https://develop.svn.wordpress.org/${WP_TESTS_TAG}/tests/phpunit/includes/ $WP_TESTS_DIR/includes
		svn co --quiet https://develop.svn.wordpress.org/${WP_TESTS_TAG}/tests/phpunit/data/ $WP_TESTS_DIR/data
	fi
	# set up testing environment wp-config entry point file if it does not exist
	if [ ! -f "$WP_TESTS_DIR"/wp-tests-config.php ]; then
	    # init testing suite entry point settings file
	    {
	        echo "<?php"
	        echo ""
	        echo "require_once('$WP_TEST_APPLICATION_DIR/vendor/autoload.php');"
            echo "require_once('$WP_TEST_APPLICATION_DIR/config/application.php');"
            echo "require_once(ABSPATH . 'wp-settings.php');"
            echo ""
            echo "define( 'WP_TESTS_DOMAIN', 'example.org' );"
            echo "define( 'WP_TESTS_EMAIL', 'admin@example.org' );"
            echo "define( 'WP_TESTS_TITLE', 'Test Blog' );"
            echo ""
            echo "define( 'WP_PHP_BINARY', 'php' );"
            echo ""
            echo "define( 'WPLANG', '' );"
         } >> "$WP_TESTS_DIR"/wp-tests-config.php

	fi
}

setup_test_db() {
    # create db user if not exists
    mysql -u "$DB_USER" -p"$DB_PASS" --execute="CREATE USER IF NOT EXISTS wp_admin_test@localhost IDENTIFIED BY 'wp_admin_test_password';"
    # delete database if it exists
    mysql -u "$DB_USER" -p"$DB_PASS" --execute="DROP DATABASE IF EXISTS wordpress_test;"
	# create database
	mysql -u "$DB_USER" -p"$DB_PASS" --execute="CREATE DATABASE wordpress_test;GRANT ALL PRIVILEGES ON wordpress_test.* TO wp_admin_test@localhost;"
	# seed database
	mysql -u "$DB_USER" -p"$DB_PASS" wordpress_test < "$WEB_ROOT_DIR/../database/clean-dump.sql"
}

migrate_test_db() {
    cd "$WP_TEST_APPLICATION_DIR"

    composer install

    # Run this so ony pending database schema can be loaded
    composer update-db
}

setup_test_application

install_test_suite

setup_test_db

migrate_test_db