"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
var ServerInfoRepository_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.ServerInfoRepository = void 0;
const common_1 = require("@nestjs/common");
const exiftool_vendored_1 = require("exiftool-vendored");
const node_child_process_1 = require("node:child_process");
const promises_1 = require("node:fs/promises");
const node_util_1 = require("node:util");
const sharp_1 = __importDefault(require("sharp"));
const system_config_dto_1 = require("../dtos/system-config.dto");
const config_repository_1 = require("./config.repository");
const logging_repository_1 = require("./logging.repository");
const exec = (0, node_util_1.promisify)(node_child_process_1.exec);
const maybeFirstLine = async (command) => {
    try {
        const { stdout } = await exec(command);
        return stdout.trim().split('\n')[0] || '';
    }
    catch {
        return '';
    }
};
const getLockfileVersion = (name, lockfile) => {
    if (!lockfile) {
        return;
    }
    const items = [...(lockfile.sources || []), ...(lockfile?.packages || [])];
    const item = items.find((item) => item.name === name);
    return item?.version;
};
let ServerInfoRepository = ServerInfoRepository_1 = class ServerInfoRepository {
    configRepository;
    logger;
    constructor(configRepository, logger) {
        this.configRepository = configRepository;
        this.logger = logger;
        this.logger.setContext(ServerInfoRepository_1.name);
    }
    async getLatestRelease(channel) {
        try {
            const { versionCheck } = this.configRepository.getEnv();
            const url = new URL(versionCheck.url);
            switch (channel) {
                case system_config_dto_1.ReleaseChannel.Stable: {
                    url.searchParams.append('channel', 'stable');
                    break;
                }
                case system_config_dto_1.ReleaseChannel.ReleaseCandidate: {
                    url.searchParams.append('channel', 'rc');
                    break;
                }
            }
            const response = await fetch(url);
            if (!response.ok) {
                throw new Error(`Version check request failed with status ${response.status}: ${await response.text()}`);
            }
            return response.json();
        }
        catch (error) {
            throw new Error('Failed to fetch latest release', { cause: error });
        }
    }
    buildVersions;
    async retrieveVersionFallback(command, commandTransform, version) {
        if (!version) {
            const output = await maybeFirstLine(command);
            version = commandTransform ? commandTransform(output) : output;
        }
        return version;
    }
    async getBuildVersions() {
        if (!this.buildVersions) {
            const { nodeVersion, resourcePaths } = this.configRepository.getEnv();
            const lockfile = await (0, promises_1.readFile)(resourcePaths.lockFile)
                .then((buffer) => JSON.parse(buffer.toString()))
                .catch(() => this.logger.warn(`Failed to read ${resourcePaths.lockFile}`));
            const [nodejsVersion, ffmpegVersion, magickVersion, exiftoolVersion] = await Promise.all([
                this.retrieveVersionFallback('node --version', undefined, nodeVersion),
                this.retrieveVersionFallback('ffmpeg -version', (output) => output.replaceAll('ffmpeg version ', ''), getLockfileVersion('ffmpeg', lockfile)),
                this.retrieveVersionFallback('magick --version', (output) => output.replaceAll('Version: ImageMagick ', ''), getLockfileVersion('imagemagick', lockfile)),
                exiftool_vendored_1.exiftool.version(),
            ]);
            const libvipsVersion = getLockfileVersion('libvips', lockfile) || sharp_1.default.versions.vips;
            this.buildVersions = {
                nodejs: nodejsVersion,
                exiftool: exiftoolVersion,
                ffmpeg: ffmpegVersion,
                libvips: libvipsVersion,
                imagemagick: magickVersion,
            };
        }
        return this.buildVersions;
    }
};
exports.ServerInfoRepository = ServerInfoRepository;
exports.ServerInfoRepository = ServerInfoRepository = ServerInfoRepository_1 = __decorate([
    (0, common_1.Injectable)(),
    __metadata("design:paramtypes", [config_repository_1.ConfigRepository,
        logging_repository_1.LoggingRepository])
], ServerInfoRepository);
//# sourceMappingURL=server-info.repository.js.map