<?php

/**
 * @file
 * Install, update and uninstall functions for the Git deploy module.
 */

/**
 * Implements hook_requirements().
 */
function git_deploy_requirements($phase) {
  $t = get_t();
  $requirements = array();
  if ($phase == 'runtime') {
    $requirements['git_deploy_git_binary'] = array(
      'title' => $t('Git binary'),
      'value' => $t('The Git binary is present and executable'),
      'severity' => function_exists('exec') && exec('git') ? REQUIREMENT_OK : REQUIREMENT_ERROR,
    );

    if ($directory = variable_get('git_deploy_file_cache_directory')) {
      $requirements['git_deploy_file_cache_directory'] = array(
        'title' => $t('Git deploy - Shared cache directory'),
        'value' => $t('The shared Git deploy temporary directory is exists and writable.'),
        'severity' => is_dir($directory) && is_writable($directory) ? REQUIREMENT_OK : REQUIREMENT_ERROR,
      );
    }
  }

  return $requirements;
}

/**
 * Implements hook_enable().
 */
function git_deploy_enable() {
  $weight = db_select('system', 's')
    ->fields('s', array('weight'))
    ->condition('s.type', 'module')
    ->condition('s.name', 'git_deploy', '<>')
    ->orderBy('s.weight')
    ->orderBy('s.name')
    ->range(0, 1)
    ->execute()
    ->fetchColumn();

  db_update('system')
    ->fields(array('weight' => $weight - 1))
    ->condition('type', 'module')
    ->condition('name', 'git_deploy')
    ->execute();
}

/**
 * Implements hook_uninstall().
 */
function git_deploy_uninstall() {
  variable_del('git_deploy_file_cache_directory');
}

/**
 * Implements hook_schema().
 */
function git_deploy_schema() {
  $table = drupal_get_schema_unprocessed('system', 'cache');
  $table['description'] = 'Cache table for git deploy to store exec command results.';
  $schema = array('cache_git_deploy' => $table);

  return $schema;
}

/**
 * Add a separate cache table.
 */
function git_deploy_update_7001() {
  if (!db_table_exists('cache_git_deploy')) {
    $table = drupal_get_schema_unprocessed('system', 'cache');
    $table['description'] = 'Cache table for git deploy to store exec command results.';
    db_create_table('cache_git_deploy', $table);
  }
}
