<?php
// Copyright 1999-2017. Plesk International GmbH. All rights reserved.

namespace Plesk\MigrationLibV8\Common\Backend;

use Plesk\MigrationLibV8\Plesk\PleskFunctions;

class ToolUtils
{
    /**
     * Prepare set of environment variables
     *
     * @param \Zend_Config $config
     * @param string|null $sectionName
     * @return array
     */
    public static function getEnvVarsByConfig(\Zend_Config $config = null, $sectionName = null)
    {
        $env = [];
        if ($config !== null) {
            foreach ($config as $key => $value) {
                if ($value instanceof \Zend_Config) {
                    $env += self::getEnvVarsByConfig($value, $key);
                    continue;
                }
                if (!in_array($key, ['ssh-password', 'windows-password', 'ftp-password', 'password'])) {
                    continue;
                }
                $rawVarName = ($sectionName ? $sectionName . '_' : '') . $key;
                $varName = str_replace('-', '_', strtoupper($rawVarName));
                $env[$varName] = PleskFunctions::decryptPassword($value);
            }
            if (false !== getenv('HOME')) {
                $env['HOME'] = getenv('HOME');
            }
        }
        $env['MIGRATOR_MESSAGES_UI'] = 'gui';
        $env['MIGRATOR_MESSAGES_LANG'] = \pm_Locale::getCode();

        // The Plesk SDK does not support parallel running of CU utilities, the mechanism used in panel-migration
        // disrupts the normal operation of the lock manager in Plesk, as it send the current token lock manager
        // to child processes. It is necessary to reset the token there.
        $env['LOCKMANAGER_CLIENT_TOKEN'] = '';
        return $env;
    }
}
