<?php

/**
 * @file
 * Installation code for Aeopus Kickstart.
 */

/**
 * Implements hook_install_tasks().
 */
function abbey_lodge_profile_install_tasks() {
  // Increase maximum function nesting level to prevent install errors.
  $max_nesting_level = ini_get('xdebug.max_nesting_level');
  if ($max_nesting_level > 0 && $max_nesting_level <= '200') {
    ini_set('xdebug.max_nesting_level', 200);
  }

  // Remove any status messages that might have been set. They are unneeded.
  drupal_get_messages('status', TRUE);

  $tasks = array();
  $current_task = variable_get('install_task', 'done');

  $tasks['abbey_lodge_profile_install_additional_modules'] = array(
    'display_name' => st('Install additional functionality'),
    'type' => 'batch',
    // Show this task only after the Kickstart steps have bene reached.
    'display' => strpos($current_task, 'abbey_lodge_profile_') !== FALSE,
  );
  $tasks['abbey_lodge_profile_import_content'] = array(
    'display_name' => st('Import content'),
    'type' => 'batch',
    // Show this task only after the Kickstart steps have bene reached.
    'display' => strpos($current_task, 'abbey_lodge_profile_') !== FALSE,
  );

  return $tasks;
}

/**
 * Implements hook_install_tasks_alter().
 */
function abbey_lodge_profile_install_tasks_alter(&$tasks, $install_state) {
  $tasks['install_finished']['function'] = 'abbey_lodge_profile_install_finished';
  $tasks['install_select_profile']['display'] = FALSE;
  $tasks['install_select_locale']['display'] = FALSE;
  $tasks['install_select_locale']['run'] = INSTALL_TASK_SKIP;

  // The "Welcome" screen needs to come after the first two steps
  // (profile and language selection), despite the fact that they are disabled.
  $new_task['install_welcome'] = array(
    'display' => TRUE,
    'display_name' => st('Welcome'),
    'type' => 'form',
    'run' => isset($install_state['parameters']['welcome']) ? INSTALL_TASK_SKIP : INSTALL_TASK_RUN_IF_REACHED,
  );
  $old_tasks = $tasks;
  $tasks = array_slice($old_tasks, 0, 2) + $new_task + array_slice($old_tasks, 2);

  // Set the installation theme.
  _abbey_lodge_profile_set_theme('seven');
}

/**
 * Force-set a theme at any point during the execution of the request.
 *
 * Drupal doesn't give us the option to set the theme during the installation
 * process and forces enable the maintenance theme too early in the request
 * for us to modify it in a clean way.
 */
function _abbey_lodge_profile_set_theme($target_theme) {
  if ($GLOBALS['theme'] != $target_theme) {
    unset($GLOBALS['theme']);

    drupal_static_reset();
    $GLOBALS['conf']['maintenance_theme'] = $target_theme;
    _drupal_maintenance_theme();
  }
}

/**
 * Task callback: shows the welcome screen.
 */
function install_welcome($form, &$form_state, &$install_state) {
  drupal_set_title(st('Welcome'));
  $message = '<p>' . st('Thank you for choosing Aeopus Kickstart, a product offered by Aeopus.') . '</p>';
  $form = array();
  $form['welcome_message'] = array(
    '#markup' => $message,
  );
  $form['actions'] = array(
    '#type' => 'actions',
  );
  $form['actions']['submit'] = array(
    '#type' => 'submit',
    '#value' => st("Let's Get Started!"),
    '#weight' => 10,
  );
  return $form;
}

function install_welcome_submit($form, &$form_state) {
  global $install_state;

  $install_state['parameters']['welcome'] = 'done';
  $install_state['parameters']['locale'] = 'en';
}

/**
 * Task callback: uses Batch API to import modules based on user selection.
 * Installs all demo store modules if requested, or any modules providing
 * additional functionality to the base install.
 *
 * Any modules providing custom blocks should be enabled here, and not before
 * (as an install profile dependency), because the themes are setup during
 * abbey_lodge_profile_install(), which means region assignment can only happen
 * after that.
 */
function abbey_lodge_profile_install_additional_modules() {
  $modules = array();

  // Resolve the dependencies now, so that module_enable() doesn't need
  // to do it later for each individual module (which kills performance).
  $files = system_rebuild_module_data();
  $modules_sorted = array();
  foreach ($modules as $module) {
    if ($files[$module]->requires) {
      // Create a list of dependencies that haven't been installed yet.
      $dependencies = array_keys($files[$module]->requires);
      $dependencies = array_filter($dependencies, '_abbey_lodge_profile_filter_dependencies');
      // Add them to the module list.
      $modules = array_merge($modules, $dependencies);
    }
  }
  $modules = array_unique($modules);
  foreach ($modules as $module) {
    $modules_sorted[$module] = $files[$module]->sort;
  }
  arsort($modules_sorted);

  $operations = array();

  // Enable themes and set as default the correct theme.
  $operations[] = array('_abbey_lodge_profile_enable_theme', array('abbey_lodge', TRUE));
  // Enable the selected modules.
  foreach ($modules_sorted as $module => $weight) {
    $operations[] = array(
      '_abbey_lodge_profile_enable_module',
      array(
        $module,
        $files[$module]->info['name'],
      ),
    );
  }
  $operations[] = array('_abbey_lodge_profile_flush_caches', array(t('Flushed caches.')));

  $batch = array(
    'title' => t('Installing additional functionality'),
    'operations' => $operations,
    'file' => drupal_get_path('profile', 'abbey_lodge_profile') . '/abbey_lodge_profile.install_callbacks.inc',
  );

  return $batch;
}

/**
 * array_filter() callback used to filter out already installed dependencies.
 */
function _abbey_lodge_profile_filter_dependencies($dependency) {
  return !module_exists($dependency);
}

/**
 * Task callback: return a batch API array with the products to be imported.
 */
function abbey_lodge_profile_import_content() {
  // Fixes problems when the CSV files used for importing have been created
  // on a Mac, by forcing PHP to detect the appropriate line endings.
  ini_set("auto_detect_line_endings", TRUE);

  // Run all available migrations.
  $migrations = migrate_migrations();
  foreach ($migrations as $machine_name => $migration) {
    $operations[] = array('_abbey_lodge_profile_import', array($machine_name, t('Importing content.')));
  }

  // Perform post-import tasks.
  $operations[] = array('_abbey_lodge_profile_post_import', array(t('Completing setup.')));

  $batch = array(
    'title' => t('Importing content'),
    'operations' => $operations,
    'file' => drupal_get_path('profile', 'abbey_lodge_profile') . '/abbey_lodge_profile.install_callbacks.inc',
  );

  return $batch;
}

/**
 * Custom installation task; perform final steps and redirect the user to the new site if there are no errors.
 *
 * @param $install_state
 *   An array of information about the current installation state.
 *
 * @return
 *   A message informing the user about errors if there was some.
 */
function abbey_lodge_profile_install_finished(&$install_state) {
  drupal_set_title(st('@drupal installation complete', array('@drupal' => drupal_install_profile_distribution_name())), PASS_THROUGH);
  $messages = drupal_set_message();

  // Remember the profile which was used.
  variable_set('install_profile', drupal_get_profile());
  variable_set('install_task', 'done');

  // Flush all caches to ensure that any full bootstraps during the installer
  // do not leave stale cached data, and that any content types or other items
  // registered by the install profile are registered correctly.
  drupal_flush_all_caches();

  // Install profiles are always loaded last
  db_update('system')
    ->fields(array('weight' => 1000))
    ->condition('type', 'module')
    ->condition('name', drupal_get_profile())
    ->execute();

  // Cache a fully-built schema.
  drupal_get_schema(NULL, TRUE);

  $customer = user_role_load_by_name('customer');
  $content_editor = user_role_load_by_name('content editor');
  $staff = user_role_load_by_name('staff');
  $room_manager = user_role_load_by_name('room manager');

  $profile = new stdClass();
  $profile->type = 'billing';
  $profile->uid = 0;
  $profile->status = 0;
  $profile->commerce_customer_address['und'][0]['name_line'] = "Carl";
  commerce_customer_profile_save($profile);

  $fields = array(
    'name' => 'carl',
    'mail' => 'carl@example.com',
    'pass' => '62kirkgate',
    'status' => 1,
    'init' => 'carl@example.com',
    'roles' => array(
      DRUPAL_AUTHENTICATED_RID => 'authenticated user',
      $customer->rid => 'customer',
      $content_editor->rid => 'content editor',
      $staff->rid => 'staff',
      $room_manager->rid => 'room manager',
    ),
    'field_billing_register' => array(
      'und' => array(
        0 => array(
          'profile_id' => $profile->profile_id,
        ),
      ),
    ),
  );
  $account = user_save('', $fields);

  $profile = new stdClass();
  $profile->type = 'billing';
  $profile->uid = 0;
  $profile->status = 0;
  $profile->commerce_customer_address['und'][0]['name_line'] = "Staff";
  commerce_customer_profile_save($profile);

  $fields = array(
    'name' => 'staff',
    'mail' => 'staff@example.com',
    'pass' => '62kirkgate',
    'status' => 1,
    'init' => 'staff@example.com',
    'roles' => array(
      DRUPAL_AUTHENTICATED_RID => 'authenticated user',
      $customer->rid => 'customer',
      $staff->rid => 'staff',
    ),
    'field_billing_register' => array(
      'und' => array(
        0 => array(
          'profile_id' => $profile->profile_id,
        ),
      ),
    ),
  );
  $account = user_save('', $fields);

  // Run cron to populate update status tables (if available) so that users
  // will be warned if they've installed an out of date Drupal version.
  // Will also trigger indexing of profile-supplied content or feeds.
  drupal_cron_run();

  if (isset($messages['error'])) {
    $output = '<p>' . (isset($messages['error']) ? st('Review the messages above before visiting <a href="@url">your new site</a>.', array('@url' => url(''))) : st('<a href="@url">Visit your new site</a>.', array('@url' => url('')))) . '</p>';
    return $output;
  }
  else {
    // Since any module can add a drupal_set_message, this can bug the user
    // when we redirect him to the front page. For a better user experience,
    // remove all the message that are only "notifications" message.
    drupal_get_messages('status', TRUE);
    drupal_get_messages('completed', TRUE);
    // Migrate adds its messages under the wrong type, see #1659150.
    drupal_get_messages('ok', TRUE);

    // If we don't install drupal using Drush, redirect the user to the front
    // page.
    if (!drupal_is_cli()) {
      if (module_exists('overlay')) {
        // Special case when no clean urls.
        $fragment = empty($GLOBALS['conf']['clean_url']) ? urlencode('?q=admin/help/getting-started') : 'admin/help/getting-started';
        drupal_goto('', array('fragment' => 'overlay=' . $fragment));
      }
      else {
        drupal_goto('admin/help/getting-started');
      }
    }
  }
}

/**
 * Implements hook_install().
 */
function abbey_lodge_profile_install() {
  // Enable the admin theme.
  $admin_theme = 'seven';
  theme_enable(array($admin_theme));
  variable_set('admin_theme', $admin_theme);
  variable_set('node_admin_theme', '1');

  // Insert default pre-defined node types into the database.
  $types = array(
    array(
      'type' => 'page',
      'name' => st('Basic page'),
      'base' => 'node_content',
      'description' => st("Use <em>basic pages</em> for your static content, such as an 'About us' page."),
      'custom' => 1,
      'modified' => 1,
      'locked' => 0,
    ),
  );

  foreach ($types as $type) {
    $type = node_type_set_defaults($type);
    node_type_save($type);
    node_add_body_field($type);
  }

  // "Basic page" configuration.
  variable_set('node_options_page', array('status'));
  variable_set('comment_page', COMMENT_NODE_HIDDEN);
  variable_set('node_submitted_page', FALSE);
  variable_set('pathauto_node_page_pattern', '[node:title]');

  // Create a default role for site administrators, with all available permissions assigned.
  $admin_role = new stdClass();
  $admin_role->name = 'administrator';
  $admin_role->weight = 2;
  user_role_save($admin_role);
  user_role_grant_permissions($admin_role->rid, array_keys(module_invoke_all('permission')));
  // Set this as the administrator role.
  variable_set('user_admin_role', $admin_role->rid);

  // Assign user 1 the "administrator" role.
  db_insert('users_roles')
    ->fields(array('uid' => 1, 'rid' => $admin_role->rid))
    ->execute();

  // Update the menu router information.
  menu_rebuild();

  // Set Mimemail.
  variable_set('mimemail_format', 'full_html');

  // Enable automatic title replacement for node bundles.
  foreach (array('node') as $entity_type) {
    $title_settings = array(
      'auto_attach' => array(
        'title' => 'title',
      ),
      'hide_label' => array(
        'entity' => 'entity',
        'page' => 0,
      ),
    );
    variable_set('title_' . $entity_type, $title_settings);
  }
  // Disable migrate autoregistration.
  variable_set('migrate_disable_autoregistration', TRUE);
}

/**
 * Disables the passed modules by removing their entries from the system table.
 *
 * Used for modules that have already disappeared from the filesystem.
 * Implemented in order to avoid the core issue described in #1081266.
 *
 * @param $modules
 *   The modules to disable.
 */
function _abbey_lodge_profile_disable_modules($modules) {
  // Disable the removed modules.
  db_update('system')
    ->fields(array('status' => 0))
    ->condition('name', $modules)
    ->condition('type', 'module')
    ->execute();
}
