"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
const readPkgUp = require("read-pkg-up");
const path = require("path");
const readPkg_1 = require("../fs/readPkg");
const writePkg = require("write-pkg");
const expandTilde_1 = require("../fs/expandTilde");
const graphController_1 = require("../fs/graphController");
const shrinkwrap_1 = require("../fs/shrinkwrap");
const modulesController_1 = require("../fs/modulesController");
const mkdirp = require("mkdirp-promise");
const normalizePath = require("normalize-path");
const rimraf = require("rimraf-then");
const pnpm_logger_1 = require("pnpm-logger");
const checkCompatibility_1 = require("./checkCompatibility");
function getContext(opts) {
    return __awaiter(this, void 0, void 0, function* () {
        const pkg = yield (opts.global ? readGlobalPkg(opts.globalPath) : readPkgUp({ cwd: opts.cwd }));
        const root = normalizePath(pkg.path ? path.dirname(pkg.path) : opts.cwd);
        const storeBasePath = resolveStoreBasePath(opts.storePath, root);
        const storePath = getStorePath(storeBasePath);
        const modulesPath = path.join(root, 'node_modules');
        let modules = yield modulesController_1.read(modulesPath);
        const isFirstInstallation = !modules;
        if (modules) {
            try {
                checkCompatibility_1.default(modules, { storePath, modulesPath });
            }
            catch (err) {
                if (opts.force) {
                    pnpm_logger_1.default.info(`Recreating ${modulesPath}`);
                    yield rimraf(modulesPath);
                    return getContext(opts);
                }
                throw err;
            }
        }
        const graph = (yield graphController_1.read(path.join(root, 'node_modules'))) || {};
        const shrinkwrap = yield shrinkwrap_1.read(root, { force: opts.force });
        const ctx = {
            pkg: pkg.pkg,
            root,
            storePath,
            graph,
            shrinkwrap,
            isFirstInstallation,
        };
        yield mkdirp(ctx.storePath);
        return ctx;
    });
}
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = getContext;
function readGlobalPkg(globalPath) {
    return __awaiter(this, void 0, void 0, function* () {
        if (!globalPath)
            throw new Error('globalPath is required');
        const globalPnpm = expandTilde_1.default(globalPath);
        const globalPkgPath = path.resolve(globalPnpm, 'package.json');
        const globalPkgJson = yield readGlobalPkgJson(globalPkgPath);
        return {
            pkg: globalPkgJson,
            path: globalPkgPath
        };
    });
}
const DefaultGlobalPkg = {
    name: 'pnpm-global-pkg',
    version: '1.0.0',
    private: true,
};
function readGlobalPkgJson(globalPkgPath) {
    return __awaiter(this, void 0, void 0, function* () {
        try {
            const globalPkgJson = yield readPkg_1.default(globalPkgPath);
            return globalPkgJson;
        }
        catch (err) {
            yield mkdirp(path.dirname(globalPkgPath));
            yield writePkg(globalPkgPath, DefaultGlobalPkg);
            return DefaultGlobalPkg;
        }
    });
}
function resolveStoreBasePath(storePath, pkgRoot) {
    if (expandTilde_1.isHomepath(storePath)) {
        return expandTilde_1.default(storePath);
    }
    return path.resolve(pkgRoot, storePath);
}
function getStorePath(storeBasePath) {
    if (underNodeModules(storeBasePath)) {
        return storeBasePath;
    }
    return path.join(storeBasePath, '1');
}
function underNodeModules(dirpath) {
    return dirpath.split(path.sep).indexOf('node_modules') !== -1;
}
//# sourceMappingURL=getContext.js.map