<?php

/**
 * @file
 * Installation functions for the Title module.
 */

/**
 * Helper function.
 */
function _title_install_set_weight($weight) {
  db_update('system')
    ->fields(array('weight' => $weight))
    ->condition('name', 'title')
    ->execute();
}

/**
 * Implements hook_install().
 */
function title_install() {
  // Make (reasonably) sure that title_module_implements_alter() is invoked as
  // last so we can determine the priority of our hook implementations reliably.
  _title_install_set_weight(100);
}

/**
 * Implements hook_disable().
 */
function title_disable() {
  foreach (field_read_fields() as $field) {
    if ($field['type'] !== 'taxonomy_term_reference') {
      continue;
    }

    if ($field['settings']['options_list_callback'] !== 'title_taxonomy_allowed_values') {
      continue;
    }

    $field['settings']['options_list_callback'] = '';
    field_update_field($field);
  }
}

/**
 * Implements hook_update_N().
 */

/**
 * Make sure Title has a very high weight to be able to perform reverse
 * synchronization reliably.
 */
function title_update_7001() {
  _title_install_set_weight(100);
}

/**
 * Update title_auto_attach variables to the new format.
 */
function title_update_7002() {
  $variables = array();

  foreach (variable_get('title_auto_attach', array()) as $variable) {
    $pieces = explode(':', $variable);
    $variables['title_' . $pieces[0]]['auto_attach'][$pieces[1]] = $pieces[1];
  }

  foreach ($variables as $name => $value) {
    variable_set($name, $value);
  }

  variable_del('title_auto_attach');
}
