#!/bin/bash

# Default values
database_name=""
db_username="root"
db_password="root"
pmc_brand=""
current_directory="$PWD"
theme_name=""
is_vip="true"
wp_version="6.3.2"
is_child="false"

# Parse positional arguments
while [[ $# -gt 0 ]]; do
  key="$1"

  case $key in
    -d|--database)
      database_name="$2"
      shift; shift;;
    -u|--username)
      db_username="$2"
      shift; shift;;
    -p|--password)
      db_password="$2"
      shift; shift;;
    -b|--brand)
      pmc_brand="$2"
      shift; shift;;
    -t|--theme)
      theme_name="$2"
      shift; shift;;
		-w|--wp)
			wp_version="$2"
			shift; shift;;
		-c|--child)
			is_child="$2"
			shift; shift;;
    -v|--vip)
      is_vip="$2"
      shift; shift;;
    *)
      shift;;
  esac
done

# Check if required options are provided
if [ -z "$pmc_brand" ]; then
  echo "Error: A Brand name is required."
  exit 1
fi

if [ -z "$theme_name" ]; then
  echo "Error: A theme slug is required."
  exit 1
fi

# Set database default to brand if not set.
if [ -z "$database_name" ]; then
  database_name="$pmc_brand"
fi

# MySQL database setup
mysql -u $db_username --password=$db_password -e "CREATE DATABASE IF NOT EXISTS $database_name"

# Create subdirectory and navigate into it
mkdir $current_directory/$pmc_brand;
cd $pmc_brand

# Run WP CLI command
# Download core.
wp core download --version=$wp_version
# Create the config file.
wp config create --dbname=$database_name --dbuser=$db_username --dbpass=$db_password
# Install WP.
wp core install --url=https://$pmc_brand.test --title="$pmc_brand" --admin_user=pmcdev --admin_password=pmcdev --admin_email=dev@pmc.com
# Shuffle salts.
wp config shuffle-salts

# Turn on debug.
config_file="$PWD/wp-config.php"

## Add additional configs.
find_string="require_once ABSPATH . 'wp-settings.php';"
config_string="define( 'SCRIPT_DEBUG', false );\\n\
define( 'WP_DEBUG_DISPLAY', false );\\n\
define( 'WP_DEBUG_LOG', true );\\n\
define( 'WP_DISABLE_FATAL_ERROR_HANDLER', true );\\n\
define( 'PMC_IS_VIP_GO_SITE', true );\\n\
define( 'VIP_GO_APP_ENVIRONMENT', 'local' );\\n\
define( 'VIP_GO_ENABLE_HTTP_CONCAT', true );\\n\
define( 'AUTOMATIC_UPDATER_DISABLED', true );\\n\
define( 'DISALLOW_FILE_EDIT', true );\\n\
define( 'DISALLOW_FILE_MODS', true );\\n\
\\n\
// Load VIP's additional requirements.\\n\
if ( file_exists( ABSPATH . '/wp-content/mu-plugins/000-pre-vip-config/requires.php' ) ) {\\n\
	require_once ABSPATH . '/wp-content/mu-plugins/000-pre-vip-config/requires.php';\\n\
}\\n\
\\n\
require_once ABSPATH . 'wp-settings.php';"
sed -i "" "s|'WP_DEBUG', false|'WP_DEBUG', true|g; s|$find_string|$config_string|g" "$config_file"

# Clone repositories
# MU Plugins
git clone git@github.com:Automattic/vip-go-mu-plugins-built.git wp-content/mu-plugins
## Copy the production memcache plugin to handle group caching issues.
git clone git@github.com:Automattic/wp-memcached.git wp-content/mu-plugins/wp-memcached
# Remove default plugins and install VIP Go plugins + pmc plugins
rm -rf wp-content/plugins
git clone git@github.com:penske-media-corp/pmc-vip-go-plugins.git wp-content/plugins
git clone git@github.com:penske-media-corp/pmc-plugins.git wp-content/plugins/pmc-plugins

# Check if required options are provided
if [ -z "$theme_name" ]; then
  echo "Theme not provided, skipping activation";
elif [ "$is_vip" = true ]; then
  git clone git@github.com:penske-media-corp/$theme_name.git wp-content/themes/vip/$theme_name
  echo "Cloned theme into vip directory.."

	if [ "$is_child" = true ]; then
		git clone git@github.com:penske-media-corp/pmc-core-v2.git wp-content/themes/vip/pmc-core-v2
	fi


	wp theme activate vip/$theme_name
elif [ "$is_vip" = false ]; then
  git clone git@github.com:penske-media-corp/$theme_name.git wp-content/themes/$theme_name
  echo "Cloned theme into themes directory."
		if [ "$is_child" = true ]; then
		git clone git@github.com:penske-media-corp/pmc-core-v2.git wp-content/themes/pmc-core-v2
	fi

	wp theme activate $theme_name
fi

# Add object cache files.
ln -s mu-plugins/query-monitor/wp-content/db.php wp-content/db.php
ln -s mu-plugins/wp-memcached/object-cache.php wp-content/object-cache.php

# Add autoloader.
client_mu="wp-content/client-mu-plugins"
mkdir $client_mu
plugin_loader="$client_mu/plugin-loader.php"
touch $plugin_loader
echo -n  "<?php
/**
 * Allow themes to load code as part of 'mu-plugins', such as when access to the
 * 'plugins_loaded' hook is required.
 *
 * Borrows VIP Go's logic for loading 'client-mu-plugins' from
 * 'mu-plugins/z-client-mu-plugins.php', which is what loads this file in the
 * first place.
 */

/**
 * Wrap in MU Plugins loaded so pmc-unit-tests has a chance to set the correct theme.
 */
add_action( 'muplugins_loaded', function() {
	\$theme_plugins_path = get_stylesheet_directory() . '/client-mu-plugins/';

	if ( wpcom_vip_should_load_plugins() && is_dir( \$theme_plugins_path ) ) {
		foreach ( wpcom_vip_get_client_mu_plugins( \$theme_plugins_path ) as \$client_mu_plugin ) {
			include_once \$client_mu_plugin;
		}

		unset( \$client_mu_plugin );
	}

	unset( \$theme_plugins_path );
} );

/**
 * We use wpcom_vip_load_plugin() in contexts that occur after the
 * 'plugins_loaded' action has already fired, which triggers a
 * _doing_it_wrong() message in our logs. We don't plan on changing our
 * approach here, so mute those notices.
 *
 * @param bool   \$trigger  Should we log the message?
 * @param string \$function Function name this was called from.
 * @param string \$message  Message that gets logged.
 * @return bool
 */
function pmc_mute_wpcom_vip_load_plugin_notice( bool \$trigger, string \$function, string \$message ): bool {
	// Check the function that fired this.
	if ( 'wpcom_vip_load_plugin' !== \$function ) {
		return \$trigger;
	}

	// The function has multiple conditionals for _doing_it_wrong(), so ensure we target the correct one.
	if ( false === strpos( \$message, 'plugins_loaded' ) ) {
		return \$trigger;
	}

	return false;
}
add_filter( 'doing_it_wrong_trigger_error', 'pmc_mute_wpcom_vip_load_plugin_notice', 10, 3 );" >> "$plugin_loader"

# Setup tests.
# Specify the PHP file
php_file="$PWD/wp-tests-config.php"
cp -r $PWD/../wordpress-develop/tests $PWD
cp $PWD/../wordpress-develop/wp-tests-config-sample.php $php_file

# Add additional test support.
test_string="
define( 'WP_ALLOW_REPAIR', true );
define( 'PMC_IS_VIP_GO_SITE', true );
define( 'VIP_GO_APP_ENVIRONMENT', 'development' );
define( 'WP_TESTS_PHPUNIT_POLYFILLS_PATH', '/Users/$USER/.composer/vendor/yoast/phpunit-polyfills/' );
"

# Replace the path to the wp codebase (but avoid echo).
sed -i "" "s|/src/|/|g; s|youremptytestdbnamehere|$database_name|g; s|yourusernamehere|$db_username|g; s|yourpasswordhere|$db_password|g; s|example.org|pmcdev.local|g; s|admin@example.org|admin@pmcdev.local|g" "$php_file"
echo -n "$test_string" >> "$php_file"
