namespace :cul do

namespace :wp do

  task :setup do
    desc "Downloads a new copy of wordpress, completely overwriting any existing site files. To install WordPress, follow this setup task with the cul:wp:install task."
    require_cap_variables!([:wp_docroot])

    unless enter_y_to_continue(color_text("This will delete all content at #{fetch(:wp_docroot)}."))
      puts 'Operation cancelled because "y" was not entered.'
      next
    end

    on roles(:web) do
      within(deploy_path) do

        # Destroy and recreate the docroot
        execute :rm, '-rf', fetch(:wp_docroot), '&&', 'mkdir', fetch(:wp_docroot)

        # Create nginx logs directory if it doesn't already exist
        execute :mkdir, '-p', deploy_path.join('logs')

        # Download and unpack latest version of WP to wp_docroot
        execute :wp, 'core', ['download', "--version=latest", "--path=#{fetch(:wp_docroot)}"]

        # Create a limited-content wp-config.php file that requires our shared
        # wp-config-include.php file. We do this so that wordpress still has a
        # wp-config.php file at the expected location, and that file correctly
        # sets the ABSPATH constant based on the wp-config.php file location.

        # Our limited-content wp-config file will only contain the following:
        # ----------------------------------------------------------
        # require dirname(__DIR__) . '/conf/the-real-conf.php';
        #
        #/* That's all, stop editing! Happy blogging. */
        #
        #/** WordPress absolute path to the Wordpress directory. */
        #if ( !defined('ABSPATH') )
        #        define('ABSPATH', dirname(__FILE__) . '/');
        #
        #/** Sets up WordPress vars and included files. */
        #require_once(ABSPATH . 'wp-settings.php');
        #?>
        # ----------------------------------------------------------
        execute :echo, '-e', '"' +
          "<?php" +
            '\\n' +
            "require dirname(__DIR__) . '/shared/wp-config-include.php';" +
            '\\n\\n' +
            "/* That's all, stop editing! Happy blogging. */" +
            '\\n' +
            "/** WordPress absolute path to the Wordpress directory. */" +
            '\\n' +
            "if ( !defined('ABSPATH') ) { define('ABSPATH', dirname(__FILE__) . '/'); }" +
            '\\n\\n' +
            "/** Sets up WordPress vars and included files. */" +
            '\\n' +
            "require_once(ABSPATH . 'wp-settings.php');" +
            '\\n' +
          "?>" +
        '"',
        '>',
        File.join(fetch(:wp_docroot), 'wp-config.php')
      end
    end

    # After setup, do a deployment so we have the latest plugins and themes
    # available and symlinked in wp-content
    invoke 'deploy'

  end

end

end