<?php
/**
 * Plugin Name: Siteway Migrator
 * Description: Deploys standalone migrator endpoint for WordPress-independent site migration.
 * Version: 2.2.0
 * Author: Siteway Oy
 * License: GPL-2.0-or-later
 *
 * This mu-plugin deploys a standalone PHP endpoint to the WordPress root.
 * The standalone file works even when WordPress is completely broken.
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

define( 'SITEWAY_MIGRATOR_KEY', '%%MIGRATOR_KEY%%' );
define( 'SITEWAY_MIGRATOR_VERSION', '2.2.0' );
define( 'SITEWAY_MIGRATOR_SOURCE', 'https://downloads.demo.siteway.fi/source/siteway-migrator-endpoint.php' );

add_action( 'init', 'siteway_migrator_deploy', 1 );

/**
 * Deploy standalone endpoint and config file to ABSPATH.
 */
function siteway_migrator_deploy() {
	$config_path     = ABSPATH . '.siteway-migrator-config.php';
	$standalone_path = ABSPATH . 'siteway-migrator.php';

	// Build current config.
	$config = [
		'version'        => SITEWAY_MIGRATOR_VERSION,
		'key'            => SITEWAY_MIGRATOR_KEY,
		'db_name'        => DB_NAME,
		'db_user'        => DB_USER,
		'db_password'    => DB_PASSWORD,
		'db_host'        => DB_HOST,
		'table_prefix'   => $GLOBALS['table_prefix'],
		'wp_content_dir' => WP_CONTENT_DIR,
		'abspath'        => ABSPATH,
	];

	// Read old config for comparison.
	$old_config  = null;
	$old_version = '';
	$old_key     = '';
	if ( file_exists( $config_path ) ) {
		if ( ! defined( 'SITEWAY_MIGRATOR' ) ) {
			define( 'SITEWAY_MIGRATOR', true );
		}
		$old_config  = @include $config_path;
		$old_version = is_array( $old_config ) ? ( $old_config['version'] ?? '' ) : '';
		$old_key     = is_array( $old_config ) ? ( $old_config['key'] ?? '' ) : '';
	}

	// Write config if changed.
	if ( $old_config !== $config ) {
		$export  = var_export( $config, true );
		$content = "<?php defined('SITEWAY_MIGRATOR') or die(); return {$export};\n";
		@file_put_contents( $config_path, $content );
	}

	// Deploy standalone if missing, version changed, key changed, or endpoint has wrong key.
	$needs_deploy = ! file_exists( $standalone_path )
		|| $old_version !== SITEWAY_MIGRATOR_VERSION
		|| $old_key !== SITEWAY_MIGRATOR_KEY;

	if ( ! $needs_deploy && file_exists( $standalone_path ) ) {
		// Verify the endpoint file actually contains the expected key.
		$endpoint_content = @file_get_contents( $standalone_path, false, null, 0, 2000 );
		if ( $endpoint_content && strpos( $endpoint_content, SITEWAY_MIGRATOR_KEY ) === false ) {
			$needs_deploy = true;
		}
	}

	if ( $needs_deploy ) {
		$response = wp_remote_get( SITEWAY_MIGRATOR_SOURCE, [ 'timeout' => 15 ] );
		if ( ! is_wp_error( $response ) && wp_remote_retrieve_response_code( $response ) === 200 ) {
			$source = wp_remote_retrieve_body( $response );
			if ( strlen( $source ) > 1000 ) {
				// Inject the key into the standalone file.
				$source = str_replace( '%%MIGRATOR_KEY%%', SITEWAY_MIGRATOR_KEY, $source );
				@file_put_contents( $standalone_path, $source );
			}
		}
	}
}
