package _VisualDVM.TestingSystem.Common;
import Common.CommonConstants;
import Common.Utils.Utils_;
import _VisualDVM.Constants;
import Common.Database.Objects.DBObject;
import _VisualDVM.Global;
import Common.Utils.TextLog;
import _VisualDVM.Utils;
import _VisualDVM.GlobalData.Account.Account;
import _VisualDVM.ProjectData.LanguageName;
import _VisualDVM.Repository.Component.Sapfor.Sapfor;
import _VisualDVM.Repository.EmailMessage;
import _VisualDVM.Repository.RepositoryRefuseException;
import _VisualDVM.Repository.RepositoryServer;
import _VisualDVM.Repository.Server.ServerCode;
import _VisualDVM.Repository.Server.ServerExchangeUnit_2021;
import _VisualDVM.TestingSystem.Common.Group.Group;
import _VisualDVM.TestingSystem.Common.MachineProcess.MachineProcess;
import _VisualDVM.TestingSystem.Common.MachineProcess.MachineProcessSet;
import _VisualDVM.TestingSystem.Common.Test.Test;
import _VisualDVM.TestingSystem.Common.Test.TestType;
import _VisualDVM.TestingSystem.Common.TestingPackageToKill.TestingPackageToKill;
import _VisualDVM.TestingSystem.DVM.DVMPackage.DVMPackage;
import _VisualDVM.TestingSystem.DVM.DVMPackage.DVMPackage_json;
import _VisualDVM.TestingSystem.DVM.DVMTestingChecker;
import _VisualDVM.TestingSystem.SAPFOR.Json.SapforPackage_json;
import _VisualDVM.TestingSystem.SAPFOR.SapforConfiguration.SapforConfiguration;
import _VisualDVM.TestingSystem.SAPFOR.SapforPackage.SapforPackage;
import _VisualDVM.TestingSystem.SAPFOR.SapforSettings.SapforSettings;
import _VisualDVM.TestingSystem.SAPFOR.SapforSettingsCommand.SapforSettingsCommand;
import _VisualDVM.TestingSystem.SAPFOR.SapforTestingPlanner;
import _VisualDVM.TestingSystem.SAPFOR.ServerSapfor.ServerSapfor;
import _VisualDVM.TestingSystem.SAPFOR.ServerSapfor.ServerSapforState;
import Visual_DVM_2021.Passes.All.DownloadRepository;
import Visual_DVM_2021.Passes.All.ZipFolderPass;
import Visual_DVM_2021.Passes.PassCode;
import Common.Passes.Pass;
import javafx.util.Pair;
import org.apache.commons.io.FileUtils;

import javax.swing.*;
import java.io.File;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.Vector;
public class TestingServer extends RepositoryServer<TestsDatabase> {
    public String name = "?";
    public static MachineProcessSet machinesProcesses = new MachineProcessSet();
    @Override
    public void afterPublishAction(DBObject object) throws Exception {
        if (object instanceof Test) {
            Test test = (Test) object;
            if (!test.unpackProjectOnServer()) {
                db.Delete(test);
                throw new RepositoryRefuseException(
                        "Не удалось прикрепить проект к тесту с id " + test.id
                                + "\nТест будет удален"
                );
            }
        } else if (object instanceof DVMPackage) {
            DVMPackage dvmPackage = (DVMPackage) object;
            //--
            Utils.CheckAndCleanDirectory(dvmPackage.getLocalWorkspace());
            //--
            dvmPackage.saveJson();
            dvmPackage.package_json = null; // объект больше не нужен.
            //--
        } else if (object instanceof SapforPackage) {
            ((SapforPackage) object).init();
        }
    }
    @Override
    public void afterDeleteAction(DBObject object) throws Exception {
        if (object instanceof Test) {
            Test test = (Test) object;
            Utils.forceDeleteWithCheck(test.getArchive());
            Utils.forceDeleteWithCheck(test.getServerPath());
        } else if (object instanceof Group) {
            Group group = (Group) object;
            Vector<Test> tests = new Vector<>();
            for (Test group_test : db.tests.Data.values()) {
                if (group_test.group_id == group.id)
                    tests.add(group_test);
            }
            for (Test group_test : tests) {
                db.Delete(group_test);
                Utils.forceDeleteWithCheck(group_test.getArchive());
                Utils.forceDeleteWithCheck(group_test.getServerPath());
            }
        } else if (object instanceof ServerSapfor) {
            Utils.forceDeleteWithCheck(
                    new File(
                            ((ServerSapfor) object).home_path
                    )
            );
        }  else if (object instanceof DVMPackage) {
            DVMPackage dvmPackage = (DVMPackage) object;
            File workspace = dvmPackage.getLocalWorkspace();
            Utils.forceDeleteWithCheck(workspace);
        } else if (object instanceof SapforPackage) {
            SapforPackage sapforPackage = (SapforPackage) object;
            File workspace = sapforPackage.getLocalWorkspace();
            Utils.forceDeleteWithCheck(workspace);
        } else if (object instanceof SapforSettings) {
            SapforSettings sapforSettings = (SapforSettings) object;
            Vector<SapforSettingsCommand> commands = new Vector<>();
            for (SapforSettingsCommand command : db.sapforSettingsCommands.Data.values()) {
                if (command.sapforsettings_id== sapforSettings.id)
                    commands.add(command);
            }
            for (SapforSettingsCommand command : commands) {
                db.Delete(command);
            }
        }
    }
    //-->>>
    @Override
    protected void beforePublishAction(DBObject object) throws Exception {
        if (object instanceof ServerSapfor) {
            int current_version = getSapforActualVersion();
            int max_installed_version = db.getInstalledSapforMaxVersion();
            if (max_installed_version == current_version)
                throw new RepositoryRefuseException("Актуальная версия SAPFOR " + max_installed_version + " уже установлена");
        }
    }
    public TestingServer() {
        super(TestsDatabase.class);
        name = Utils_.getDateName("testingServer");
        System.out.println("ServerName=" + Utils_.Brackets(name));
    }
    //основа
    @Override
    public int getPort() {
        return Global.properties.TestingServerPort;
    }
    //---
    @Override
    protected void startAdditionalThreads() {
        testingThread.start();
    }
    DVMTestingChecker dvmTestingChecker = new DVMTestingChecker();
    SapforTestingPlanner sapforTestingPlanner = new SapforTestingPlanner();
    //--
    protected Thread testingThread = new Thread(() -> {
        while (true) {
            dvmTestingChecker.Perform();
            sapforTestingPlanner.Perform();
            Utils_.sleep(5000);
        }
    });
    //------>>>
    public static Timer checkTimer = null;
    public static void TimerOn() {
        checkTimer = new Timer(Global.properties.CheckTestingIntervalSeconds * 1000, e -> {
            Global.mainModule.getPass(PassCode.ActualizePackages).Do();
        });
        checkTimer.start();
    }
    public static void TimerOff() {
        if (checkTimer != null)
            checkTimer.stop();
    }
    public static void ResetTimer() {
        TimerOff();
        TimerOn();
    }
    @Override
    protected void Session() throws Exception {
        Test test;
        int test_id;
        switch (code) {
            case PerformAutoSapforTesting:
                Print("Запустить автоматическое тестирование SAPFOR");
                TextLog Log = new TextLog();
                SapforPackage autoPackage = tryAutoSapforTesting(Log);
                response = new ServerExchangeUnit_2021(ServerCode.OK);
                EmailMessage message = Log.isEmpty() ?
                        new EmailMessage(
                                "Запущено автоматическое тестирование версии " + request.arg + " системы SAPFOR",
                                "Пакет "+ Utils_.Brackets(autoPackage.id), new Vector<>()) :
                        new EmailMessage(
                                "Не удалось запустить автоматическое тестирование версии " + request.arg + " системы SAPFOR",
                                Log.toString(),
                                new Vector<>()
                        );
                Email(message);
                break;
            case DownloadTest:
                Print("Отправить клиенту тест " + request.arg);
                test_id = Integer.parseInt(request.arg);
                if (db.tests.containsKey(test_id)) {
                    test = db.tests.get(test_id);
                    response = new ServerExchangeUnit_2021(ServerCode.OK, "", Utils_.fileToBytes(test.getArchive()));
                } else
                    throw new RepositoryRefuseException("Теста с именем " + request.arg + " не существует");
                break;
            case ReceiveTestsDatabase:
                Print("Получить базу данных тестов");
                response = new ServerExchangeUnit_2021(ServerCode.OK);
                response.object = Utils_.fileToBytes(db.getFile());
                break;
            //---
            case RefreshDVMTests:
                Print("Синхронизировать репозиторий тестов ");
                response = new ServerExchangeUnit_2021(ServerCode.OK);
                RefreshDVMTests((Account) request.object, Integer.parseInt(request.arg));
                break;
            case DVMPackageNeedsKill:
                Print("Проверить нуждается ли пакет DVM в убийстве");
                DVMPackageNeedsKill();
                break;
            case UpdateActiveDVMPackages:
                Print("Получить данные по пакетам DVM");
                UpdateActiveDVMPackages();
                break;
            case GetFirstActiveSapforPackages:
                Print("Получить первый активный пакет задач SAPFOR");
                GetFirstActiveSapforPackages();
                break;
            case SapforPackageNeedsKill:
                Print("Проверить нуждает ли пакет SAPFOR в убийстве");
                SapforPackageNeedsKill();
                break;
            case UpdateActiveSapforPackages:
                Print("Получить данные по пакетам Sapfor");
                UpdateActiveSapforPackages();
                break;
            case DownloadDVMPackage:
                Print("Загрузить пакет DVM");
                DownloadDVMPackage();
                break;
            case DownloadDVMPackages:
                Print("Загрузить пакеты DVM");
                DownloadDVMPackages();
                break;
            case DownloadSapforPackage:
                Print("Загрузить пакет SAPFOR");
                DownloadSapforPackage();
                break;
            case ReplaceTestCode:
                Print("Заменить код теста");
                ReplaceTestCode();
                break;
            case ReplaceTestsCodes:
                Print("Заменить код тестов");
                ReplaceTestsCodes();
                break;
            case GetSapforPackagesJson:
                Print("Получить информацию о задачах пакетов SAPFOR");
                GetSapforPackagesJson();
                break;
            case GetDVMPackagesJson:
                Print("Получить информацию о задачах пакетов DVM");
                GetDVMPackagesJson();
                break;
            case GetFirstActiveDVMPackageForMachineURL:
                Print("Получить первый активный пакет задач DVM на машине с адресом");
                GetFirstActiveDVMPackageForMachineURL();
                break;
            case GetServerName:
                Print("Получить имя сервера");
                GetServerName();
                break;
            case StartNecessaryMachines:
                Print("Проверка процессов машин");
                response = new ServerExchangeUnit_2021(ServerCode.OK);
                StartNecessaryMachines();
                break;
            case GetSapforForCompilation:
                Print("Получить первую активную версию Sapfor для сборки");
                GetSapforForCompilation();
                break;
            case GetMaxSapforVersion:
                Print("Получить максимальную установленную версию Sapfor");
                GetSapforMaxVersion();
                break;
            default:
                throw new RepositoryRefuseException("Неподдерживаемый код: " + code);
        }
    }
    //->>
    Pair<Group, Vector<File>> ConvertDirectoryToGroup(File src, LanguageName languageName, TestType
            testType, Account account) throws Exception {
        Group object = new Group();
        Vector<File> groupFiles = null; //транспорт.
        //->>
        object.description = src.getName();
        object.language = languageName;
        object.type = testType;
        object.sender_name = account.name;
        object.sender_address = account.email;
        //-->>
        File[] files = src.listFiles(pathname ->
                pathname.isFile()
                        && !pathname.getName().equals("settings")
                        && !pathname.getName().equals("test-analyzer.sh")
                        && Utils_.getExtension(pathname).startsWith(languageName.getDVMCompile()));
        ;
        if (files != null) {
            groupFiles = new Vector<>(Arrays.asList(files));
            groupFiles.sort(Comparator.comparing(File::getName));
        }
        //->>
        return new Pair<>(object, groupFiles);
    }
    public void RefreshDVMTests(Account account, int sapfor_id) throws Exception {
        ServerSapfor sapfor = null;
        if (!db.serverSapfors.containsKey(sapfor_id))
            throw new RepositoryRefuseException("Версия SAPFOR  с ключом " + sapfor_id + " не найдена.");
        sapfor = db.serverSapfors.get(sapfor_id);
        DownloadRepository downloadRepository = new DownloadRepository();
        if (!downloadRepository.Do())
            throw new RepositoryRefuseException("Не удалось обновить репозиторий");
        //-->>
        Vector<Pair<Group, Vector<File>>> groups = new Vector<>();
        File testsSrc = Paths.get(
                Global.RepoDirectory.getAbsolutePath(),
                "dvm", "tools", "tester", "trunk", "test-suite").toFile();
        LanguageName[] supportedLanguages = new LanguageName[]{LanguageName.fortran, LanguageName.c};
        for (LanguageName languageName : supportedLanguages) {
            for (TestType testType : TestType.values()) {
                File groupsSrc = null;
                switch (testType) {
                    case Correctness:
                        String languageSrcName = null;
                        switch (languageName) {
                            case fortran:
                                languageSrcName = "Fortran";
                                break;
                            case c:
                                languageSrcName = "C";
                                break;
                        }
                        if (languageSrcName != null) {
                            groupsSrc = Paths.get(testsSrc.getAbsolutePath(), "Correctness", languageSrcName).toFile();
                            File[] groupsDirs = groupsSrc.listFiles(File::isDirectory);
                            if (groupsDirs != null) {
                                for (File groupDir : groupsDirs)
                                    groups.add(ConvertDirectoryToGroup(groupDir, languageName, testType, account));
                            }
                        }
                        break;
                    case Performance:
                        File groupDir = Paths.get(testsSrc.getAbsolutePath(), "Performance").toFile();
                        groups.add(ConvertDirectoryToGroup(groupDir, languageName, testType, account));
                        break;
                }
            }
        }
        groups.sort(Comparator.comparing(o -> o.getKey().description));
        //-теперь создать тесты.
        //--
        for (Pair<Group, Vector<File>> p : groups)
            db.RefreshGroup(account, sapfor, p);
    }
    private void GetFirstActiveSapforPackages() throws Exception {
        response = new ServerExchangeUnit_2021(ServerCode.OK);
        response.object = db.getFirstActiveSapforPackagesCopies();
    }
    void GetSapforMaxVersion() throws Exception {
        response = new ServerExchangeUnit_2021(ServerCode.OK);
        response.object = db.getInstalledSapforMaxVersion();
    }
    void UpdateActiveDVMPackages() throws Exception {
        response = new ServerExchangeUnit_2021(ServerCode.OK);
        Vector<Pair<Integer, Long>> keys_pairs = (Vector<Pair<Integer, Long>>) request.object;
        Vector<DVMPackage> res = new Vector<>();
        //--
        for (Pair<Integer, Long> p : keys_pairs) {
            if (db.dvmPackages.containsKey(p.getKey())) {
                DVMPackage actual = db.dvmPackages.get(p.getKey());
                if (actual.ChangeDate != p.getValue())
                    res.add(new DVMPackage(actual));
            }
        }
        response.object = res;
    }
    private void UpdateActiveSapforPackages() {
        response = new ServerExchangeUnit_2021(ServerCode.OK);
        Vector<Pair<Integer, Long>> keys_pairs = (Vector<Pair<Integer, Long>>) request.object;
        Vector<SapforPackage> res = new Vector<>();
        //--
        for (Pair<Integer, Long> p : keys_pairs) {
            if (db.sapforPackages.containsKey(p.getKey())) {
                SapforPackage actual = db.sapforPackages.get(p.getKey());
                if (actual.ChangeDate != p.getValue())
                    res.add(new SapforPackage(actual));
            }
        }
        response.object = res;
    }
    private void DVMPackageNeedsKill() {
        response = new ServerExchangeUnit_2021(ServerCode.OK);
        response.object = CommonConstants.Nan;
        int packageId = (int) request.object;
        for (TestingPackageToKill packageToKill : db.testingPackagesToKill.Data.values()) {
            if ((packageToKill.packageId == packageId) && (packageToKill.type == 0)) {
                response.object = packageToKill.id;
                break;
            }
        }
    }
    private void SapforPackageNeedsKill() throws Exception {
        response = new ServerExchangeUnit_2021(ServerCode.OK);
        response.object = CommonConstants.Nan;
        int packageId = (int) request.object;
        for (TestingPackageToKill packageToKill : db.testingPackagesToKill.Data.values()) {
            if ((packageToKill.packageId == packageId) && (packageToKill.type == 1)) {
                response.object = packageToKill.id;
                break;
            }
        }
    }
    private void DownloadDVMPackage() throws Exception {
        int dvmPackage_id = (int) request.object;
        if (!db.dvmPackages.containsKey(dvmPackage_id))
            throw new RepositoryRefuseException("Не найдено пакета тестирования DVM с ключом " + dvmPackage_id);
        response = new ServerExchangeUnit_2021(ServerCode.OK);
        DVMPackage dvmPackage = db.dvmPackages.get(dvmPackage_id);
        File workspace = dvmPackage.getLocalWorkspace();
        File results_zip = new File(workspace, "results.zip");
        File package_json = dvmPackage.getJsonFile();
        response.object = new Pair(Utils_.fileToBytes(results_zip), Utils_.fileToBytes(package_json));
    }
    private void DownloadDVMPackages() throws Exception {
        Vector<Integer> ids = (Vector<Integer>) request.object;
        Vector<Pair<Integer, Pair<byte[], byte[]>>> res = new Vector<>();
        for (int dvmPackage_id : ids) {
            if (!db.dvmPackages.containsKey(dvmPackage_id))
                throw new RepositoryRefuseException("Не найдено пакета тестирования DVM с ключом " + dvmPackage_id);
            DVMPackage dvmPackage = db.dvmPackages.get(dvmPackage_id);
            File workspace = dvmPackage.getLocalWorkspace();
            File results_zip = new File(workspace, "results.zip");
            File package_json = dvmPackage.getJsonFile();
            res.add(new Pair<>(dvmPackage_id, new Pair(Utils_.fileToBytes(results_zip), Utils_.fileToBytes(package_json))));
        }
        response = new ServerExchangeUnit_2021(ServerCode.OK);
        response.object = res;
    }
    private void DownloadSapforPackage() throws Exception {
        int sapforPackage_id = (int) request.object;
        if (!db.sapforPackages.containsKey(sapforPackage_id))
            throw new RepositoryRefuseException("Не найдено пакета тестирования SAPFOR с ключом " + sapforPackage_id);
        response = new ServerExchangeUnit_2021(ServerCode.OK);
        SapforPackage sapforPackage = db.sapforPackages.get(sapforPackage_id);
        File workspace = sapforPackage.getLocalWorkspace();
        File results_zip = Utils.getTempFileName("results");
        ZipFolderPass zipFolderPass = new ZipFolderPass();
        zipFolderPass.Do(workspace.getAbsolutePath(), results_zip.getAbsolutePath());
        if (results_zip.exists())
            response.object = Utils_.fileToBytes(results_zip);
        else
            throw new RepositoryRefuseException("Не удалось заархивировать пакет тестирования SAPFOR с ключом " + sapforPackage_id);
    }
    private void ReplaceTestCode() throws Exception {
        Test test = (Test) request.object;
        response = new ServerExchangeUnit_2021(ServerCode.OK);
        //---
        if (!test.unpackProjectOnServer()) {
            db.Delete(test);
            throw new RepositoryRefuseException(
                    "Не удалось прикрепить проект к тесту с id " + test.id
                            + "\nТест будет удален"
            );
        } else db.Update(test); //обновить список файлов и размерность.
    }
    private void ReplaceTestsCodes() throws Exception {
        Vector<Test> tests = (Vector<Test>) request.object;
        response = new ServerExchangeUnit_2021(ServerCode.OK);
        for (Test test : tests) {
            if (!test.unpackProjectOnServer()) {
                db.Delete(test);
                throw new RepositoryRefuseException(
                        "Не удалось прикрепить проект к тесту с id " + test.id
                                + "\nТест будет удален"
                );
            } else db.Update(test); //обновить список файлов и размерность.
        }
    }
    private void GetDVMPackagesJson() throws Exception {
        Vector<Integer> packages_ids = (Vector<Integer>) request.object;
        Vector<DVMPackage_json> jsons = new Vector<>();
        for (int package_id : packages_ids) {
            if (!db.dvmPackages.containsKey(package_id))
                throw new RepositoryRefuseException("Пакета задач DVM " + Utils_.Brackets(package_id) + " не существует.");
            DVMPackage dvmPackage = db.dvmPackages.get(package_id);
            File json = dvmPackage.getJsonFile();
            if (!json.exists())
                throw new RepositoryRefuseException("Не найден JSON файл для пакета задач DVM " + Utils_.Brackets(package_id));
            jsons.add((DVMPackage_json) Utils_.jsonFromFile(json, DVMPackage_json.class));
        }
        response = new ServerExchangeUnit_2021(ServerCode.OK);
        response.object = jsons;
    }
    private void GetSapforPackagesJson() throws Exception {
        Vector<Integer> packages_ids = (Vector<Integer>) request.object;
        Vector<SapforPackage_json> jsons = new Vector<>();
        for (int package_id : packages_ids) {
            if (!db.sapforPackages.containsKey(package_id))
                throw new RepositoryRefuseException("Пакета задач SAPFOR " + Utils_.Brackets(package_id) + " не существует.");
            SapforPackage sapforPackage = db.sapforPackages.get(package_id);
            File json = sapforPackage.getJsonFile();
            if (!json.exists())
                throw new RepositoryRefuseException("Не найден JSON файл для пакета задач SAPFOR " + Utils_.Brackets(package_id));
            jsons.add((SapforPackage_json) Utils_.jsonFromFile(json, SapforPackage_json.class));
        }
        response = new ServerExchangeUnit_2021(ServerCode.OK);
        response.object = jsons;
    }
    private void GetServerName() throws Exception {
        response = new ServerExchangeUnit_2021(ServerCode.OK);
        response.object = name;
    }
    //--
    private void GetFirstActiveDVMPackageForMachineURL() {
        response = new ServerExchangeUnit_2021(ServerCode.OK);
        response.object = db.getFirstActiveDVMPackageCopyForMachineURL(request.arg);
    }
    void StartNecessaryMachines() {
        try {
            Vector<String> aborted = new Vector<>();
            for (MachineProcess process : machinesProcesses.Data.values()) {
                if (process.isAborted()) {
                    aborted.add(process.id);
                }
            }
            //---
            for (String key : aborted) {
                machinesProcesses.Data.remove(key);
            }
            //---
            LinkedHashMap<String, MachineProcess> processes_to_start = new LinkedHashMap<>();
            //1. Получить список всех пакетов, которые активны, и взять из них машины.
            for (DVMPackage dvmPackage : db.dvmPackages.Data.values()) {
                if (dvmPackage.state.isActive()) {
                    //-
                    if (!machinesProcesses.hasProcessForPackage(dvmPackage)) {
                        MachineProcess new_process = new MachineProcess(dvmPackage);
                        processes_to_start.put(new_process.getUniqueKey(), new_process);
                    }
                }
            }
            //запуск.
            for (MachineProcess process : processes_to_start.values()) {
                process.Start();
                if (Utils.checkFileCreation(process.getStartedFile())) {
                    machinesProcesses.Data.put(process.id, process);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    void GetSapforActualVersion() throws Exception {
        response = new ServerExchangeUnit_2021(ServerCode.OK);
        File versionFile = new File(Global.TempDirectory, "version.h");
        if (versionFile.exists())
            FileUtils.forceDelete(versionFile);
        //1. Получить версию из репозитория.
        Utils.startScript(Global.TempDirectory,
                Global.TempDirectory,
                "get_version",
                "wget --user dvmhuser --password dvmh2013  -P " +
                        Utils_.DQuotes(Global.TempDirectory.getAbsolutePath()) +
                        "  http://svn.dvm-system.org/svn/dvmhrepo/sapfor/experts/Sapfor_2017/_src/Utils/version.h"
        ).waitFor();
        if (!versionFile.exists())
            throw new RepositoryRefuseException("Не удалось загрузить текущую версию SAPFOR из репозитория!");
        int current_version = Sapfor.readVersionFromCode(versionFile);
        int max_installed_version = db.getInstalledSapforMaxVersion();
        if (max_installed_version == current_version)
            throw new RepositoryRefuseException("Версия " + max_installed_version + " уже установлена");
    }
    //---
    int getSapforActualVersion() throws Exception {
        File versionFile = new File(Global.TempDirectory, "version.h");
        if (versionFile.exists())
            FileUtils.forceDelete(versionFile);
        //1. Получить версию из репозитория.
        Utils.startScript(Global.TempDirectory,
                Global.TempDirectory,
                "get_version",
                "wget --user dvmhuser --password dvmh2013  -P " +
                        Utils_.DQuotes(Global.TempDirectory.getAbsolutePath()) +
                        "  http://svn.dvm-system.org/svn/dvmhrepo/sapfor/experts/Sapfor_2017/_src/Utils/version.h"
        ).waitFor();
        if (!versionFile.exists())
            throw new RepositoryRefuseException("Не удалось загрузить текущую версию SAPFOR из репозитория!");
        return Sapfor.readVersionFromCode(versionFile);
    }
    void GetSapforForCompilation() throws Exception {
        //1. Проверить наличие заказов от пользователя
        ServerSapfor serverSapfor = db.getSapforCopyForCompilation();
        if (serverSapfor == null) {
            //2 если нет. проверить есть ли свежие версии.
            int max_version = db.getInstalledSapforMaxVersion();
            int current_version = getSapforActualVersion();
            if (current_version > max_version) {
                serverSapfor = new ServerSapfor();
                serverSapfor.sender_name = "server";
                serverSapfor.sender_address = Constants.MailAddress;
                serverSapfor.state = ServerSapforState.Queued;
                db.Insert(serverSapfor);
            }
        }
        response = new ServerExchangeUnit_2021(ServerCode.OK);
        response.object = serverSapfor;
    }
    SapforPackage tryAutoSapforTesting(TextLog Log) throws Exception {
        //--
        Account account = new Account();
        account.name = "server";
        account.email = Constants.MailAddress;
        //-
        int sapforId = Integer.parseInt(request.arg);
        System.out.println("Sapfor_id = "+request.arg);

        if (!db.serverSapfors.containsKey(sapforId)) {
            Log.Writeln_("Версия SAPFOR " + sapforId + " не существует.");
            return null;
        }
        ServerSapfor sapfor = db.serverSapfors.get(sapforId);
        if (!sapfor.state.equals(ServerSapforState.Done)) {
            Log.Writeln_("Выбранная версия SAPFOR " + sapforId + " не собрана!");
            return null;
        }
        Vector<SapforConfiguration> configurations = db.sapforConfigurations.getAutoConfigurations();
        if (configurations.isEmpty()) {
            Log.Writeln_("Не найдено конфигураций для автоматического тестирования!");
            return null;
        }
        SapforPackage target = new SapforPackage(account,
                sapfor,
                configurations,
                1,
                Log);
        //-
        if (target.tasksCount == 0) {
            Log.Writeln_("Не сформировано ни одной новой задачи.");
            return null;
        }
        beforePublishAction(target);
        db.InsertS(target);
        afterPublishAction(target);
        //--
        return target;
    }

}

