<?php

/*
Plugin Name: Generate Fake Sites
Description: WP-CLI command to create fake sites
*/

if ( ! defined( 'ABSPATH' ) ) die( "Cannot access directly." );

if ( defined( 'WP_CLI' ) && WP_CLI ) {

	class GenerateFakeSites extends WP_CLI_Command {

		/**
		 *  @synopsis <number_of_sites>
		 */
		public function generate( $args, $assoc_args ) {

			if ( !isset( $_SERVER['REMOTE_ADDR'] ) ) {
				$_SERVER['REMOTE_ADDR'] = '127.0.0.1';
			}

			if ( !isset( $args[0] ) || !is_numeric( $args[0] ) || intval( $args[0] ) != $args[0] ) {
				WP_CLI::error( "Invalid number of sites" );
				die();
			}

			$num_sites = $args[0];
			$num_sites_int = intval( $num_sites );

			for ( $site_index = 0; $site_index < $num_sites_int; $site_index++ ) {

				// $blog_name = Generate_Fake_Sites_UUID::v4();
				$blog_name = NewGUID();
				$user_name = $blog_name;
				$password = wp_generate_password( 40 );
				$email = $blog_name . '@localhost';

				$user_id = wpmu_create_user( $user_name, $password, $email );

				$domain = parse_url( network_site_url(), PHP_URL_HOST );
				$slug = strtolower( $blog_name );

				$slug . '.' . parse_url( network_site_url(), PHP_URL_HOST );
				$meta = array();

				$blog_id = wpmu_create_blog( $domain, $slug, $blog_name, $user_id, array( 'public' => 1 ) );
				do_action( 'wpmu_activate_blog', $blog_id, $user_id, $password, $blog_name, $meta );

				WP_CLI::success( sprintf( 'Created site %s', $domain . '/' . $slug ) );

			}
		}
	}

	WP_CLI::add_command( 'generate_fake_sites', 'GenerateFakeSites' );

}

/**
 * Generate a UUID without needing PHP's uuid extension
 *
 * @see http://www.largeresource.com/21/call-to-undefined-function-uuid_create-in-php
 * @return string UUID
 */
function NewGUID() {
	$guidstr = "";
	for ( $i=1;$i <= 16;$i++ ) {
		$b = (int)rand( 0, 0xff );
		if ( $i == 7 ) { $b &= 0x0f; $b |= 0x40; } // version 4 (random)
		if ( $i == 9 ) { $b &= 0x3f; $b |= 0x80; } // variant
		$guidstr .= sprintf( "%02s", base_convert( $b, 10, 16 ) );
		if ( $i == 4 || $i == 6 || $i == 8 || $i == 10 ) { $guidstr .= '-'; }
	}
	return $guidstr;
}
