<?php

# Default is file cache engine
$engine = 'File';

# Check for APC
if (extension_loaded('apc') && function_exists('apc_dec') && (php_sapi_name() !== 'cli' || ini_get('apc.enable_cli'))) {
	$engine = 'Apc';
}

# Localhost defaults to file cache engine
if (LOCALHOST) {
	$engine = 'File';
}

# Define the engine
define('CACHE_ENGINE', $engine);

# In development mode, caches should expire quickly.
$duration = '+999 days';
if (Configure::read('debug') >= 1) {
	$duration = '+10 seconds';
}

# Prefix each application on the same server with a different string, to avoid Memcache and APC conflicts.
$explode = explode(DS, ROOT);
define('CACHE_PREFIX', end($explode) . '_');

try {

	/**
	 * Configure the cache used for general framework caching.    Path information,
	 * object listings, and translation cache files are stored with this configuration.
	 */
	Cache::config('_cake_core_', [
		'engine'    => $engine,
		'prefix'    => CACHE_PREFIX . 'cake_core_',
		'path'      => CACHE . 'persistent' . DS,
		'serialize' => ($engine === 'File'),
		'duration'  => $duration
	]);

	/**
	 * Configure the cache for model and datasource caches.     This cache configuration
	 * is used to store schema descriptions, and table listings in connections.
	 */
	Cache::config('_cake_model_', [
		'engine'    => $engine,
		'prefix'    => CACHE_PREFIX . 'cake_model_',
		'path'      => CACHE . 'models' . DS,
		'serialize' => ($engine === 'File'),
		'duration'  => $duration
	]);

	# Caching for format helper
	Cache::config('format', [
		'engine'    => CACHE_ENGINE,
		'prefix'    => CACHE_PREFIX . 'format_',
		'path'      => CACHE . 'format' . DS,
		'serialize' => false,
		'duration'  => '+1 week'
	]);

	# Live caching
	Cache::config('live', [
		'engine'    => CACHE_ENGINE,
		'prefix'    => CACHE_PREFIX . 'live_',
		'path'      => CACHE . 'live' . DS,
		'serialize' => false,
		'duration'  => '+1 year'
	]);

} catch (Exception $e) {

	// If cache folder not writable
	if (!is_writable(CACHE)) {
		die(__('Cache dir is not writable (%s)', CACHE));
	}

	// Recreate cache dirs
	$cacheDirs = [
		'data',
		'format',
		'live',
		'models',
		'pages',
		'persistent',
		'view'
	];

	foreach ($cacheDirs as $dir) {
		if (!is_dir(CACHE . $dir)) {
			mkdir(CACHE . $dir);
		}
	}
}

