/****************************************************************************
**
** Copyright (C) 2023 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the tools applications of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

// Put here the first version number of the qt.tools.qtcreator which contains only sdktool.
// Do not update the version after that.
var SDKTOOL_VERSION = "9.0.1-0-202212100000";
var qtCreatorAutoDependencyComponents = new Array();

// constructor
function Component()
{

    if (installer.value("os") == "win") {
        var vcredist_msvc_32 = "qt.tools.vcredist_msvc2019_x86";
        var vcredist_msvc_64 = "qt.tools.vcredist_msvc2019_x64";
        var vcredist_32 = "qt.tools.vcredist";
        var vcredist_64 = "qt.tools.vcredist_64";
        if (installer.componentByName(vcredist_msvc_64) &&
           installer.componentByName(vcredist_msvc_32) &&
           installer.componentByName(vcredist_64) &&
           installer.componentByName(vcredist_32)) {
            // Creator needs vcredist 32bit on windows
            component.addDependency(vcredist_msvc_32);
            // for OpenSSL
            component.addDependency(vcredist_32);
            if (systemInfo.currentCpuArchitecture == "x86_64") {
                component.addDependency(vcredist_msvc_64);
                // for OpenSSL
                component.addDependency(vcredist_64);
            }
        }
    }

    if (installer.value("os") == "x11") {
        // set installation directory
        installer.setValue("EmbeddedInstallationRootDir", "/usr/local/Trolltech");
        installer.setValue("EmbeddedToolchainDir", "/usr/local/angstrom/arm");
    }

    // Following code is required for splitting the sdktool from QtCreator. qt.tools.qtcreator component includes
    // now only sdktool and qt.tools.qtcreator_gui the actual QtCreator. If the QtCreator is already installed
    // with name qt.tools.qtcreator, we need to select qt.tools.qtcreator_gui for install so it won't vanish.
    // All qt.tools.qtcreator sub components are renamed as qt.tools.qtcreator_gui.* so those needs to be selected
    // for install as well.
    var qtCreatorGui = installer.componentByName("qt.tools.qtcreator_gui");
    if (!qtCreatorGui)
        return;

    if (component.isInstalled() && !qtCreatorGui.isInstalled()) {
        var installedVersion = component.value("InstalledVersion");
        console.log("QtCreator installed version: " + installedVersion);
        if (installer.versionMatches(installedVersion, "<" + SDKTOOL_VERSION )) {// 'Old' qt.tools.qtcreator installed, SDKtool not
            // Add temporary autodependency to creator gui and its dependencies, so it won't vanish when we update the
            // qt.tools.qtcreator which contains only sdktool
            if (installer.isUpdater()) {
                console.log("SDKtool split from QtCreator");
                //Get existing autodependency values if any so we can revert the temporary AutoDependOn
                //which we need when updating the existing installation
                qtCreatorGui.setValue("AutoDependOn", "qt.tools.qtcreator," + qtCreatorGui.value("AutoDependOn"));
                qtCreatorAutoDependencyComponents.push(qtCreatorGui);
                // Force update for replacabled components, all qt.tools.qtcreator child components are replaced with _gui
                // e.g. qt.tools.qtcreator.src -> qt.tools.qtcreator_gui.src.
                var subGuiComponents = installer.components("qt.tools.qtcreator_gui.");
                for (var i = 0; i < subGuiComponents.length; i++) {
                    var subGuiComponent = subGuiComponents[i];
                    var subComponentToReplace = subGuiComponent.name.replace("_gui", "");
                    var replacableComponent = installer.componentByName(subComponentToReplace);
                    if (replacableComponent && replacableComponent.isInstalled()) {
                        // Add temporary AutoDependOn so that the sub components will be installed with correct id
                        subGuiComponent.setValue("AutoDependOn", "qt.tools.qtcreator," + subGuiComponent.value("AutoDependOn"));
                        qtCreatorAutoDependencyComponents.push(subGuiComponent);
                        console.log("Install sub gui component: " + subGuiComponent.name);
                        console.log("Replaced sub component:" + replacableComponent.name);
                        // Original qt.tools.qtcreator.telemetry is installed as autodependency to qt.tools.qtcreator.
                        // AutoDependency is set in script, depending on if user has selected it for install or not.
                        // qt.tools.qtcreator_gui.telemetry does not have correct autodependency to qt.tools.qtcreator_gui
                        // so we set it here when we see that the original qt.tools.qtcreator.telemetry is installed and
                        // replaced with qt.tools.qtcreator_gui.telemetry
                        if (subGuiComponent.name == "qt.tools.qtcreator_gui.telemetry") {
                            subGuiComponent.setValue("AutoDependOn", "qt.tools.qtcreator_gui," + subGuiComponent.value("AutoDependOn"));
                        }
                    }
                }
            } else if (installer.isPackageManager()) {
                // Hide the new QtCreator gui as it is already installed with the old qt.tools.qtcreator
                // component. It is forced installation anyways so it cannot be uninstalled here.
                qtCreatorGui.setValue("Virtual", true);
            }
        }
    }
}

Component.prototype.createOperationsForArchive = function(archive)
{
    component.createOperationsForArchive(archive);
    setSDKToolBinaryPaths(installer.value("TargetDir"));
    copyQtCreatorSharedSettingsFile();
}

Component.prototype.createOperations = function()
{
    // Call the base createOperations and afterwards set some registry settings
    component.createOperations();
    var maintenanceToolPath;

    if (installer.value("os") == "win") {
        maintenanceToolPath = installer.value("TargetDir") + "/MaintenanceTool.exe";
    } else if (installer.value("os") == "x11") {
        maintenanceToolPath = installer.value("TargetDir") + "/MaintenanceTool";
    } else if (installer.value("os") == "mac") {
        maintenanceToolPath = installer.value("TargetDir")
                + "/MaintenanceTool.app/Contents/MacOS/MaintenanceTool";
    }

    var settingsFile = installer.value("QtCreatorInstallerSettingsFile");
    if (!installer.isOfflineOnly()) {
        // Configure UpdateInfo plugin
        component.addOperation("Settings", "path="+settingsFile, "method=set",
                               "key=Updater/MaintenanceTool",
                               "value="+maintenanceToolPath);
        component.addOperation("Settings", "path="+settingsFile,
                               "method=add_array_value",
                               "key=Plugins/ForceEnabled", "value=UpdateInfo");
    }
}

function setSDKToolBinaryPaths(value)
{
    if (installer.value("os") == "win") {
        installer.setValue("QtCreatorInstallerSettingsFile_OLD", value + "/Tools/QtCreator/share/qtcreator/QtProject/QtCreator.ini");
        installer.setValue("QtCreatorInstallerSettingsFile", value + "//Tools/sdktool/share/qtcreator/QtProject/QtCreator.ini");
        installer.setValue("SDKToolBinary", value + "\\/Tools/sdktool\\bin\\sdktool.exe");
        // TARGET_INSTALL_DIR "/Tools/sdktool" was "/Tools/QtCreator":
        installer.setValue("SDKToolBinary_OLD", value + "\\Tools\\QtCreator\\bin\\sdktool.exe")
    } else if (installer.value("os") == "mac") {
        installer.setValue("QtCreatorInstallerSettingsFile_OLD", value + "/Qt Creator.app/Contents/Resources/QtProject/QtCreator.ini");
        installer.setValue("QtCreatorInstallerSettingsFile", value + "//Tools/sdktool/QtProject/QtCreator.ini");
        installer.setValue("SDKToolBinary_OLD", value + "/Qt Creator.app/Contents/Resources/libexec/sdktool");
        installer.setValue("SDKToolBinary", value + "//Tools/sdktool/libexec/sdktool");
    } else {
        installer.setValue("QtCreatorInstallerSettingsFile_OLD", value + "/Tools/QtCreator/share/qtcreator/QtProject/QtCreator.ini");
        installer.setValue("QtCreatorInstallerSettingsFile", value + "//Tools/sdktool/share/qtcreator/QtProject/QtCreator.ini");
        installer.setValue("SDKToolBinary", value + "//Tools/sdktool/libexec/qtcreator/sdktool");
        // TARGET_INSTALL_DIR "/Tools/sdktool" was "/Tools/QtCreator":
        installer.setValue("SDKToolBinary_OLD", value + "/Tools/QtCreator/libexec/qtcreator/sdktool")
    }
}

function copyQtCreatorSharedSettingsFile()
{
    // check if the QtCreator settings file is in the old location -> copy to new location
    if (installer.value("os") == "win") {
        var oldPath = installer.value("TargetDir") + "/Tools/QtCreator/share/qtcreator/QtProject";
        var oldQtCIniFile = oldPath + "/QtCreator.ini";
        var newPath = installer.value("TargetDir") + "//Tools/sdktool/share/qtcreator/QtProject";
    } else if (installer.value("os") == "mac") {
        var oldPath = installer.value("TargetDir") + "/Qt Creator.app/Contents/Resources/QtProject";
        var oldQtCIniFile = oldPath + "/QtCreator.ini";
        var newPath = installer.value("TargetDir") + "//Tools/sdktool/QtProject";
    } else {
        var oldPath = installer.value("TargetDir") + "/Tools/QtCreator/share/qtcreator/QtProject";
        var oldQtCIniFile = oldPath + "/QtCreator.ini";
        var newPath = installer.value("TargetDir") + "//Tools/sdktool/share/qtcreator/QtProject";
    }

    if (installer.fileExists(newPath)) {
        console.log("Qt Creator settings exist at new location, not moving.");
        // already copied to new path
        return;
    }
    if (!installer.fileExists(oldQtCIniFile)) {
        console.log("Qt Creator settings do not exist at old location, not moving.");
        // old settings don't exist
        return;
    }

    // copy the settings directory to new location
    console.log("Moving Qt Creator settings from \"" + oldPath + "\" to \"" + newPath + "\"");
    var newPathPlusQtcreator = newPath + "/qtcreator";
    try {
        installer.performOperation("Mkdir", [newPathPlusQtcreator]);
    } catch (e) {
        console.log("Failed to create directory \"" + newPathPlusQtcreator + "\"");
        return;
    }
    var filesToMove = [
        "QtCreator.ini",
        "qtcreator/cmaketools.xml",
        "qtcreator/debuggers.xml",
        "qtcreator/devices.xml",
        "qtcreator/profiles.xml",
        "qtcreator/qtversion.xml",
        "qtcreator/toolchains.xml",
        "qtcreator/android.xml",
        "qtcreator/abi.xml"
    ];
    filesToMove.forEach(function(file) {
        var oldFile = oldPath + "/" + file;
        var newFile = newPath + "/" + file;
        try {
            installer.performOperation("Move", [oldFile, newFile]);
        } catch (e) {
            console.log("Failed to move \"" + oldFile + "\" to \"" + newFile + "\"");
        }
    });

    try {
        installer.performOperation("Rmdir", [oldPath + "/qtcreator"]);
        installer.performOperation("Rmdir", [oldPath]);
    } catch (e) {
        console.log("Failed to remove old Qt Creator settings directory \"" + oldPath + "\"");
    }
}

Component.prototype.beginInstallation = function()
{

    // Reset the original AutoDependOn value. We have temporarily set the AutoDependOn to
    // qt.tools.qtcreator so that the qt.tools.qtcreator_gui and its child components are installed at update.
    for (var i = 0; i < qtCreatorAutoDependencyComponents.length; i++) {
        var guiComponent = qtCreatorAutoDependencyComponents[i];
        if (!guiComponent)
            continue;
        var autoDependencies = guiComponent.value("AutoDependOn");
        autoDependencies = autoDependencies.replace("qt.tools.qtcreator,", "");
        guiComponent.setValue("AutoDependOn", autoDependencies);
    }
    component.beginInstallation();
}
