<?php

// @see ID-11478 Run the 'config.inc.php' once more AFTER the update to ensure proper values for cloud and active features.
global $g_absdir, $g_comp_database_system, $g_db_system, $g_admin_auth, $g_crypto_hash, $g_disable_addon_upload, $g_enable_gui_update, $g_license_token, $licenseService, $g_security, $g_is_cloud, $g_active_features;

$configurationTemplate = $g_absdir . '/setup/config_template.inc.php';
$configurationTarget = $g_absdir . '/src/config.inc.php';

$configurationData = [
    '%config.adminauth.username%'                   => array_keys($g_admin_auth)[0],
    '%config.adminauth.password%'                   => $g_admin_auth[array_keys($g_admin_auth)[0]],
    '%config.db.type%'                              => $g_db_system['type'],
    '%config.db.host%'                              => $g_db_system['host'],
    '%config.db.port%'                              => $g_db_system['port'],
    '%config.db.username%'                          => $g_db_system['user'],
    '%config.db.password%'                          => $g_db_system['pass'],
    '%config.db.name%'                              => $g_db_system['name'],
    '%config.crypt.hash%'                           => $g_crypto_hash,
    '%config.admin.disable_addon_upload%'           => $g_disable_addon_upload,
    '%config.admin.enable_gui_update%'              => $g_enable_gui_update ?? 1,
    '%config.license.token%'                        => $g_license_token,
    '%config.security.passwords_encryption_method%' => $g_security['passwords_encryption_method'],
    '%config.cloud.active%'                         => is_numeric($g_is_cloud) ? (int)$g_is_cloud : 0,
    '%config.active_features.list%'                 => is_array($g_active_features) ? implode("','", $g_active_features) : '',
];

$g_migration_log[] = '<span class="bold">Migrate configuration file for older versions</span>';

if (!file_exists($configurationTemplate)) {
    $g_migration_log[] = '<span class="text-red">Config template ' . $configurationTemplate . ' does not exist.</span>';
}

if (!is_writable(dirname($configurationTarget))) {
    $g_migration_log[] = '<span class="text-red">Folder ' . dirname($configurationTarget) . ' is not writeable.</span>';
}

if (file_exists($configurationTarget) && !is_writable($configurationTarget)) {
    $g_migration_log[] = '<span class="text-red">Config file ' . dirname($configurationTarget) . ' is not writeable.</span>';
}

if (isys_file_put_contents($configurationTarget, strtr(file_get_contents($configurationTemplate), $configurationData))) {
    if (function_exists('opcache_get_configuration') && opcache_get_configuration() !== false) {
        opcache_invalidate($configurationTarget, true);
    }
}

$g_migration_log[] = '<span class="bold">Migration finished!</span>';
