"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 (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const ipfs_client_1 = require("ipfs-client");
const ipfs_core_1 = require("ipfs-core");
const pth = __importStar(require("path"));
const child_process_1 = require("child_process");
const fs_1 = __importDefault(require("fs"));
const rrdir_1 = __importDefault(require("rrdir"));
class Retrieval {
    static getClient(api) {
        return (0, ipfs_client_1.create)({
            http: api
        });
    }
    static async resolve(ipfs, path) {
        if (!path.startsWith('singularity://')) {
            console.error('Unsupported protocol. The path needs to start with singularity://, i.e. singularity://ipns/index.dataset.io/path/to/folder');
            process.exit(1);
        }
        const splits = path.slice('singularity:/'.length).split('/');
        const ipns = splits.slice(0, 3).join('/');
        path = splits.slice(3).join('/');
        const resolved = await ipfs.dag.resolve(ipns);
        const segments = [];
        for (const segment of path.split('/')) {
            if (segment !== '') {
                segments.push('entries', segment);
            }
        }
        const innerPath = segments.join('/');
        return [resolved.cid, innerPath];
    }
    static async show(api, path) {
        const ipfs = Retrieval.getClient(api);
        const [resolved, innerPath] = await Retrieval.resolve(ipfs, path);
        let dagResult;
        try {
            dagResult = await ipfs.dag.get(resolved, {
                path: innerPath + '/sources'
            });
        }
        catch (error) {
            console.error(error.message);
            process.exit(1);
        }
        if (dagResult.remainderPath !== undefined && dagResult.remainderPath.length > 0) {
            console.error(`Remainder path cannot be resolved: ${dagResult.remainderPath}`);
            process.exit(1);
        }
        return dagResult.value;
    }
    static async list(api, path) {
        const ipfs = Retrieval.getClient(api);
        const [resolved, innerPath] = await Retrieval.resolve(ipfs, path);
        const dagResult = await ipfs.dag.get(resolved, {
            path: innerPath
        });
        if (dagResult.remainderPath !== undefined && dagResult.remainderPath.length > 0) {
            console.error(`Remainder path cannot be resolved: ${dagResult.remainderPath}`);
            process.exit(1);
        }
        const index = dagResult.value;
        if (index.type === 'file') {
            return [{
                    type: index.type,
                    size: index.size,
                    name: index.name
                }];
        }
        else {
            const result = [];
            const entries = index.entries;
            for (const name in entries) {
                const entry = entries[name];
                if (entry instanceof ipfs_core_1.CID) {
                    result.push({
                        name, type: 'dir', size: 0
                    });
                }
                else {
                    result.push({
                        name, type: 'file', size: entry.size
                    });
                }
            }
            return result;
        }
    }
    static async cp(api, path, dest, providers) {
        const ipfs = Retrieval.getClient(api);
        const [resolved, innerPath] = await Retrieval.resolve(ipfs, path);
        const dagResult = await ipfs.dag.get(resolved, {
            path: innerPath
        });
        if (dagResult.remainderPath !== undefined && dagResult.remainderPath.length > 0) {
            console.error(`Remainder path cannot be resolved: ${dagResult.remainderPath}`);
            process.exit(1);
        }
        const node = dagResult.value;
        const tempDir = pth.resolve(dest, '.fetching');
        const tempPath = pth.resolve(dest, '.fetching', node.name);
        const sources = dagResult.value.sources;
        for (const source of sources) {
            let success = false;
            for (const provider of providers) {
                console.log(`Checking whether ${source.dataCid} can be retrieved from ${provider}`);
                const result = (0, child_process_1.spawnSync)('lotus', ['client', 'ls', '--maxPrice', '0', '--miner', provider, source.dataCid], { timeout: 10000 });
                if (result.signal || result.status !== 0) {
                    console.error(result.stderr.toString());
                    continue;
                }
                console.log(`${provider} has the piece ${source.dataCid}. Start retrieving...`);
                fs_1.default.rmSync(tempDir, { recursive: true, force: true });
                fs_1.default.mkdirSync(tempDir, { recursive: true });
                const selector = source.selector.map((n) => `Links/${n}/Hash`).join('/');
                const retrieveResult = (0, child_process_1.spawnSync)('lotus', ['client', 'retrieve', '--maxPrice', '0', '--miner', provider, '--data-selector', selector, source.dataCid, tempPath], { stdio: 'inherit' });
                if (retrieveResult.signal || retrieveResult.status !== 0) {
                    console.error(retrieveResult.stderr.toString());
                    continue;
                }
                console.log(`Retrieved ${source.dataCid} from ${provider} to ${tempPath}.`);
                success = true;
                break;
            }
            if (!success) {
                console.error('Cleaning up temporary files');
                fs_1.default.rmSync(tempDir, { recursive: true, force: true });
                process.exit(1);
            }
            for (const entry of rrdir_1.default.sync(tempDir, { stats: true })) {
                const relative = pth.relative(tempDir, entry.path);
                const target = pth.join(dest, relative);
                if (entry.directory) {
                    console.log(`mkdir ${target}`);
                    fs_1.default.mkdirSync(target, { recursive: true });
                }
                else {
                    if (!fs_1.default.existsSync(target)) {
                        console.log(`mv ${entry.path} to ${target}`);
                        fs_1.default.renameSync(entry.path, target);
                    }
                    else {
                        console.log(`Appending ${entry.path} to ${target}`);
                        const r = fs_1.default.createReadStream(entry.path);
                        const w = fs_1.default.createWriteStream(target, { flags: 'a' });
                        await Retrieval.pipe(r, w);
                    }
                }
            }
            fs_1.default.rmSync(tempDir, { recursive: true, force: true });
        }
        console.log('Succeeded');
    }
    static async pipe(r, w) {
        r.pipe(w);
        return new Promise(function (resolve, reject) {
            r.on('end', resolve);
            r.on('error', reject);
        });
    }
}
exports.default = Retrieval;
//# sourceMappingURL=Retrieval.js.map