"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());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
const path = require("path");
const findUp = require("find-up");
const fs = require("mz/fs");
const runScript_1 = require("../runScript");
const readPkg_1 = require("../fs/readPkg");
const pnpmNodeModules = findUp.sync('node_modules', { cwd: __dirname });
const nodeGyp = path.resolve(pnpmNodeModules, 'node-gyp/bin/node-gyp.js');
function postInstall(root, log) {
    return __awaiter(this, void 0, void 0, function* () {
        const pkg = yield readPkg_1.default(root);
        const scripts = pkg && pkg.scripts || {};
        if (!scripts['install']) {
            yield checkBindingGyp(root, log);
        }
        if (scripts['install']) {
            yield npmRunScript('install');
            return;
        }
        yield npmRunScript('preinstall');
        yield npmRunScript('postinstall');
        return;
        function npmRunScript(scriptName) {
            return __awaiter(this, void 0, void 0, function* () {
                if (!scripts[scriptName])
                    return;
                return runScript_1.default('npm', ['run', scriptName], { cwd: root, log });
            });
        }
    });
}
exports.default = postInstall;
/**
 * Run node-gyp when binding.gyp is available. Only do this when there's no
 * `install` script (see `npm help scripts`).
 */
function checkBindingGyp(root, log) {
    return __awaiter(this, void 0, void 0, function* () {
        try {
            yield fs.stat(path.join(root, 'binding.gyp'));
        }
        catch (err) {
            if (err.code === 'ENOENT') {
                return;
            }
        }
        return runScript_1.default(nodeGyp, ['rebuild'], { cwd: root, log });
    });
}
//# sourceMappingURL=postInstall.js.map