<?php



@error_reporting ( E_ALL ^ E_WARNING ^ E_NOTICE );
@ini_set ( 'display_errors', true );
@ini_set ( 'html_errors', false );
@ini_set ( 'error_reporting', E_ALL ^ E_WARNING ^ E_NOTICE );

define( 'DATALIFEENGINE', true );
define( 'ROOT_DIR', substr( dirname(  __FILE__ ), 0, -13 ) );
define( 'ENGINE_DIR', ROOT_DIR . '/engine' );

include ENGINE_DIR . '/data/config.php';

date_default_timezone_set ( $config['date_adjust'] );

require_once ENGINE_DIR . '/classes/mysql.php';
require_once ENGINE_DIR . '/data/dbconfig.php';
require_once ENGINE_DIR . '/modules/functions.php';


ini_set("memory_limit","512M");
set_time_limit(0);

$_TIME = time();

require_once ENGINE_DIR . '/kodik/func.php';


if ( !$config['allow_cache'] ) $config['allow_cache'] = 1;

$config_kodik = unserialize( file_get_contents( ENGINE_DIR . '/data/kodik_grabber.config' ) );
if ( !$config_kodik ) $config_kodik = array();

if (file_exists(__DIR__.'/lock.txt') && (time()-filectime(__DIR__.'/lock.txt'))>2*3600 ) {
	@unlink(__DIR__.'/lock.txt');
}


if (file_exists(__DIR__.'/lock.txt')) {
	die('locked');
}

$secret_key = $config_kodik['secret_key'];


if (!$secret_key) {
	die('secret key is required');
}


if (!isset($argv)) {
	echo 'php -f '.$_SERVER['SCRIPT_FILENAME'].' films you_password 2>&1 &<br>';
	echo 'php -f '.$_SERVER['SCRIPT_FILENAME'].' serials you_password 2>&1 &<br>';
	echo 'php -f '.$_SERVER['SCRIPT_FILENAME'].' anime you_password 2>&1 &<br>';
	echo 'php -f '.$_SERVER['SCRIPT_FILENAME'].' anime-serials you_password 2>&1 &<br>';
	die();
}

$type = $argv[1];

$key = $argv[2];

if ($key != $secret_key) {
	die('bad secret key');
}

if (!in_array($type, ['films', 'serials', 'anime', 'anime-serials'])) {
	die('not alowed type');
}


$urls = [
	'films'         => 'https://dumps.kodik.biz/films.json',
	'serials'       => 'https://dumps.kodik.biz/serials.json',
	'anime-serials' => 'https://dumps.kodik.biz/serials/anime-serial.json',
	'anime'         => 'https://dumps.kodik.biz/anime.json'
];

$url = $urls[$type];


file_put_contents(__DIR__.'/lock.txt', '');

include ENGINE_DIR . '/kodik/class.php';
$kodik = new Kodik($db, $config_kodik);
$kodik->start($url);

@unlink(__DIR__.'/lock.txt');


?>