<?php
/**
 * 将根目录 GeoLite2-Country.mmdb 移动并重命名到隐蔽路径
 *
 *   php tools/setup_geoip_db.php
 */
$root = dirname(__DIR__);
require_once $root . '/cong.php';

$source = $root . '/GeoLite2-Country.mmdb';
$target = defined('CLOAK_GEOIP_DB_PATH') ? CLOAK_GEOIP_DB_PATH : $root . '/storage/runtime/c7f2a9e1/cc_idx.dat';
$targetDir = dirname($target);

$result = [
    'ok'     => false,
    'source' => $source,
    'target' => $target,
    'msg'    => '',
];

if (is_file($target)) {
    $result['ok']  = true;
    $result['msg'] = '目标文件已存在，跳过';
    echo json_encode($result, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT) . "\n";
    exit(0);
}

if (!is_file($source)) {
    $result['msg'] = '源文件不存在：' . $source;
    echo json_encode($result, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT) . "\n";
    exit(1);
}

if (!is_dir($targetDir)) {
    if (!@mkdir($targetDir, 0755, true) && !is_dir($targetDir)) {
        $result['msg'] = '无法创建目录：' . $targetDir;
        echo json_encode($result, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT) . "\n";
        exit(1);
    }
}

if (!@rename($source, $target)) {
    if (!@copy($source, $target)) {
        $result['msg'] = '移动/复制失败';
        echo json_encode($result, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT) . "\n";
        exit(1);
    }
    @unlink($source);
}

$htaccess = $targetDir . '/.htaccess';
if (!is_file($htaccess)) {
    @file_put_contents($htaccess, "Deny from all\n");
}

$result['ok']  = true;
$result['msg'] = 'GeoIP 数据库已就绪';
echo json_encode($result, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT) . "\n";
