<?php
$config_dir = __DIR__.'/../config';
$config_path = $config_dir.'/config.ini';
$dbopen_path = __DIR__.'/../dbopen.php';

if (!file_exists($config_path) && file_exists($dbopen_path)) {
	include $dbopen_path;
	if (isset($db['host'], $db['dbname'], $db['user'], $db['pass'])) {
		if (!is_dir($config_dir)) {
			mkdir($config_dir, 0755, true);
		}
        
		$ini = "[database]\n";
		$ini .= "host = \"{$db['host']}\"\n";
		$ini .= "dbname = \"{$db['dbname']}\"\n";
		$ini .= "user = \"{$db['user']}\"\n";
		$ini .= "pass = \"{$db['pass']}\"\n";
		
		$result = file_put_contents($config_path, $ini);
		
		if ($result !== false) {
			$dbopen_data = "<?php\n";
      $dbopen_data .= "\$config = parse_ini_file(__DIR__.'/config/config.ini', true);\n";
			$dbopen_data .= "\$db['host'] = \$config['database']['host'];\n";
			$dbopen_data .= "\$db['dbname'] = \$config['database']['dbname'];\n";
			$dbopen_data .= "\$db['user'] = \$config['database']['user'];\n";
			$dbopen_data .= "\$db['pass'] = \$config['database']['pass'];\n";
			file_put_contents($dbopen_path, $dbopen_data);
		}
	}
}