"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.sshManager = void 0;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const os_detector_1 = require("../utils/os-detector");
const docker_run_1 = require("./docker-run");
const docker_volume_1 = require("./docker-volume");
const DEFAULT_VOLUME_NAME = 'runestone-ssh';
const SSH_MOUNT_PATH = '/root/.ssh';
const PRIVATE_KEY_NAMES = new Set(['id_rsa', 'id_ecdsa', 'id_ed25519', 'id_dsa']);
function isPrivateKeyFile(filePath) {
    return PRIVATE_KEY_NAMES.has(path.basename(filePath));
}
function quoteForShell(value) {
    return `'${value.replace(/'/g, `'\\''`)}'`;
}
function ensureVolume(volumeName) {
    if (!docker_volume_1.volumeService.exists(volumeName)) {
        docker_volume_1.volumeService.createVolume(volumeName);
    }
}
function writeFileToVolume(volumeName, basename, content, mode) {
    const target = `${SSH_MOUNT_PATH}/${basename}`;
    const fileMode = mode ?? '644';
    docker_run_1.runService.run('alpine:latest', ['sh', '-c', 'dd of="$1"; chmod "$2" "$1"', 'sh', target, fileMode], {
        rm: true,
        interactive: true,
        volumes: [{ source: volumeName, target: SSH_MOUNT_PATH }],
        input: content
    });
}
exports.sshManager = {
    scanHomeDirectory() {
        const sshDir = os_detector_1.osDetector.sshDir();
        if (!fs.existsSync(sshDir)) {
            return [];
        }
        return fs
            .readdirSync(sshDir)
            .map((file) => path.join(sshDir, file))
            .filter((file) => fs.statSync(file).isFile() && isPrivateKeyFile(file));
    },
    listKeys(volumeName = DEFAULT_VOLUME_NAME) {
        try {
            const output = docker_run_1.runService.run('alpine:latest', [
                'sh',
                '-c',
                'for f in "$1"/*; do [ -f "$f" ] || continue; case "$f" in *.pub) continue;; esac; basename "$f"; done',
                'sh',
                SSH_MOUNT_PATH
            ], {
                rm: true,
                volumes: [{ source: volumeName, target: SSH_MOUNT_PATH }]
            });
            return output
                .split(/\r?\n/)
                .map((line) => line.trim())
                .filter(Boolean);
        }
        catch {
            return [];
        }
    },
    addKey(keyPath, volumeName = DEFAULT_VOLUME_NAME) {
        const absolutePath = path.resolve(keyPath);
        if (!fs.existsSync(absolutePath)) {
            throw new Error(`SSH key not found: ${absolutePath}`);
        }
        if (!fs.statSync(absolutePath).isFile()) {
            throw new Error(`SSH key is not a file: ${absolutePath}`);
        }
        if (!isPrivateKeyFile(absolutePath)) {
            throw new Error(`File '${path.basename(absolutePath)}' is not a supported SSH private key name`);
        }
        ensureVolume(volumeName);
        const basename = path.basename(absolutePath);
        writeFileToVolume(volumeName, basename, fs.readFileSync(absolutePath, 'utf8'), '600');
        const publicKeyPath = `${absolutePath}.pub`;
        if (fs.existsSync(publicKeyPath) && fs.statSync(publicKeyPath).isFile()) {
            writeFileToVolume(volumeName, `${basename}.pub`, fs.readFileSync(publicKeyPath, 'utf8'));
        }
        return true;
    },
    addKeys(keys, volumeName = DEFAULT_VOLUME_NAME) {
        const keyPaths = keys ?? this.scanHomeDirectory();
        for (const keyPath of keyPaths) {
            this.addKey(keyPath, volumeName);
        }
    }
};
//# sourceMappingURL=ssh-manager.js.map