<?php

/**
 * i-doit - Updates
 *
 * Migrating QCW profiles to every tenant.
 *
 * @package     i-doit
 * @subpackage  Update
 * @copyright   synetics GmbH
 * @license     http://www.i-doit.com/license
 * @author      Leonard Fischer <lfischer@i-doit.com>
 */

/**
 * @var $g_comp_database isys_component_database
 */
global $g_comp_database, $g_absdir, $g_mandator_info, $g_comp_database_system;

// Set migrationId
$g_migration_identifier = 'qcw_profiles_migration';

// Check whether migration was executed before
if ($this->is_migration_done($g_migration_identifier)) {
    $g_migration_log[] = '<span class="bold">Migration of <strong>Q</strong>uick <strong>C</strong>onfiguration <strong>W</strong>izard profiles has already been done.</span>';
} else {
    $sourcePath = $g_absdir . '/imports/qcw/';
    $destinationPath = $sourcePath . isys_helper_upload::prepare_filename($g_mandator_info['isys_mandator__dir_cache']) . '/';

    $files = glob($sourcePath . '*.xml');

    if (!mkdir($destinationPath) && !is_dir($destinationPath)) {
        $g_migration_log[] = '<span class="bold red">The new directory <code>' . $destinationPath . '</code> could not be created, please check the rights and try again!</span>';
    } else {
        $g_migration_log[] = '<span class="bold">Starting Migration of <strong>Q</strong>uick <strong>C</strong>onfiguration <strong>W</strong>izard profiles.</span>';
        $g_migration_log[] = 'Moving <strong>' . count($files) . ' profiles</strong> from <code style="margin:0 5px;">/imports/qcw/</code> to <code style="margin:0 5px;">/imports/qcw/' . isys_helper_upload::prepare_filename($g_mandator_info['isys_mandator__dir_cache']) . '/</code>';

        foreach ($files as $file) {
            $file = basename($file);

            if (copy($sourcePath . $file, $destinationPath . $file)) {
                $g_migration_log[] = '<span class="indent green">Moving profile "' . $file . '"</span>';
            } else {
                $g_migration_log[] = '<span class="indent red">Moving profile "' . $file . '" did not work</span>';
            }
        }

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

        // Mark migration as done
        $this->migration_done($g_migration_identifier);
    }
}
