"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
Object.defineProperty(exports, "ServerUpdateService", {
    enumerable: true,
    get: function() {
        return ServerUpdateService;
    }
});
const _envutils = require("../../utils/env.utils");
const _serverconstants = require("../../server.constants");
const _child_process = require("child_process");
const _runtimeexceptions = require("../../exceptions/runtime.exceptions");
class ServerUpdateService {
    simpleGitService;
    logger;
    constructor({ simpleGitService, loggerFactory }){
        this.simpleGitService = simpleGitService;
        this.logger = loggerFactory(ServerUpdateService.name);
    }
    async restartServer() {
        if (!(0, _envutils.isPm2)() && !(0, _envutils.isNodemon)()) {
            throw new _runtimeexceptions.InternalServerException("Restart requested, but no daemon was available to perform this action");
        }
        if ((0, _envutils.isPm2)()) {
            (0, _child_process.execSync)(`pm2 restart ${_serverconstants.AppConstants.pm2ServiceName}`, {
                timeout: 5000
            });
            return true;
        } else if ((0, _envutils.isNodemon)()) {
            (0, _child_process.execSync)("echo '// Restart file for nodemon' > ./nodemon_restart_trigger.js", {
                timeout: 5000
            });
            return true;
        }
    }
    async checkGitUpdates() {
        let isValidGitRepo = this.simpleGitService.checkIsRepo();
        if (!isValidGitRepo) {
            throw new _runtimeexceptions.ValidationException("Server update could not proceed as the server had no .git repository folder");
        }
        await this.simpleGitService.fetch();
        const localRepoStatus = await this.simpleGitService.status();
        if (!localRepoStatus) return;
        const result = {
            gitFolderFound: true,
            updateCheckSuccess: true,
            commitsBehind: localRepoStatus.behind,
            commitsAhead: localRepoStatus.ahead,
            filesModified: localRepoStatus.modified?.length,
            status: "",
            pullStatus: null
        };
        if (localRepoStatus?.behind === 0) {
            result.status = "No commits to pull";
            return result;
        }
        if (localRepoStatus?.modified?.length > 0 || localRepoStatus.ahead !== 0) {
            result.status = "Files were modified or the repo was commits ahead - cannot pull safely";
            return result;
        }
        this.logger.warn("Pulling git to get the latest server updates");
        const pullDetails = await this.simpleGitService.pull();
        result.status = "Pull action completed";
        result.pullStatus = pullDetails;
        return result;
    }
}

//# sourceMappingURL=server-update.service.js.map