"use strict";
/* Copyright 2013 Joseph Spencer.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
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());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
var fs = __importStar(require("fs"));
var path = __importStar(require("path"));
var cp = __importStar(require("child_process"));
var which_1 = __importDefault(require("which"));
var winreg_1 = __importDefault(require("winreg"));
var child_process_1 = require("child_process");
var isWindows = process.platform.indexOf('win') === 0;
var jdkRegistryKeyPaths = [
    "\\SOFTWARE\\JavaSoft\\JDK",
    "\\SOFTWARE\\JavaSoft\\Java Development Kit"
];
var jreRegistryKeyPaths = [
    "\\SOFTWARE\\JavaSoft\\Java Runtime Environment"
];
function findJavaHome(optionsOrCb, optional) {
    return __awaiter(this, void 0, void 0, function () {
        var cb, options, res, err, error_1;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    if (!optional) {
                        cb = optionsOrCb;
                        options = undefined;
                    }
                    else {
                        options = optionsOrCb;
                        cb = optional;
                    }
                    res = undefined;
                    err = null;
                    _a.label = 1;
                case 1:
                    _a.trys.push([1, 3, , 4]);
                    return [4 /*yield*/, findJavaHomePromise(options)];
                case 2:
                    res = _a.sent();
                    return [3 /*break*/, 4];
                case 3:
                    error_1 = _a.sent();
                    err = error_1;
                    return [3 /*break*/, 4];
                case 4:
                    cb(err, res);
                    return [2 /*return*/];
            }
        });
    });
}
function findJavaHomePromise(options) {
    return __awaiter(this, void 0, void 0, function () {
        var allowJre, JAVA_FILENAME, regs, possibleKeyPaths, javaHome;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    allowJre = !!(options && options.allowJre);
                    JAVA_FILENAME = (allowJre ? 'java' : 'javac') + (isWindows ? '.exe' : '');
                    regs = (options && options.registry) ? [options.registry] : ["x64", "x86"];
                    // From env
                    if (process.env.JAVA_HOME && dirIsJavaHome(process.env.JAVA_HOME, JAVA_FILENAME)) {
                        return [2 /*return*/, process.env.JAVA_HOME];
                    }
                    if (!isWindows) return [3 /*break*/, 2];
                    possibleKeyPaths = allowJre ? jdkRegistryKeyPaths.concat(jreRegistryKeyPaths) : jdkRegistryKeyPaths;
                    return [4 /*yield*/, findInRegistry(possibleKeyPaths, regs)];
                case 1:
                    javaHome = _a.sent();
                    if (javaHome) {
                        return [2 /*return*/, javaHome];
                    }
                    _a.label = 2;
                case 2: return [4 /*yield*/, findInPath(JAVA_FILENAME)];
                case 3: 
                // From PATH
                return [2 /*return*/, _a.sent()];
            }
        });
    });
}
function findInPath(JAVA_FILENAME) {
    return new Promise(function (resolve) {
        which_1.default(JAVA_FILENAME, function (err, proposed) {
            if (err || !proposed) {
                return resolve(null);
            }
            if (/\.jenv\/shims/.test(proposed)) {
                try {
                    var jenvProposed = child_process_1.execSync("jenv which " + JAVA_FILENAME).toString().trim();
                    proposed = jenvProposed;
                }
                catch (ex) {
                    console.error(ex);
                }
            }
            //resolve symlinks
            proposed = findLinkedFile(proposed);
            //get the /bin directory
            proposed = path.dirname(proposed);
            //on mac, java install has a utility script called java_home that does the
            //dirty work for us
            var macUtility = path.resolve(proposed, 'java_home');
            if (fs.existsSync(macUtility)) {
                var buffer = void 0;
                try {
                    buffer = cp.execSync(macUtility, { cwd: proposed });
                    var javaHome = '' + buffer.toString().replace(/\n$/, '');
                    return resolve(javaHome);
                }
                catch (error) {
                    return resolve(null);
                }
            }
            //up one from /bin
            resolve(path.dirname(proposed));
        });
    });
}
function findInRegistry(keyPaths, regArchs) {
    return __awaiter(this, void 0, void 0, function () {
        var promises, _i, regArchs_1, arch, _a, keyPaths_1, keyPath, keysFoundSegments, keysFound, sortedKeysFound, _b, sortedKeysFound_1, key, res;
        return __generator(this, function (_c) {
            switch (_c.label) {
                case 0:
                    if (!keyPaths.length)
                        return [2 /*return*/, null];
                    promises = [];
                    for (_i = 0, regArchs_1 = regArchs; _i < regArchs_1.length; _i++) {
                        arch = regArchs_1[_i];
                        for (_a = 0, keyPaths_1 = keyPaths; _a < keyPaths_1.length; _a++) {
                            keyPath = keyPaths_1[_a];
                            promises.push(promisifyFindPossibleRegKey(keyPath, arch));
                        }
                    }
                    return [4 /*yield*/, Promise.all(promises)];
                case 1:
                    keysFoundSegments = _c.sent();
                    keysFound = Array.prototype.concat.apply([], keysFoundSegments);
                    if (!keysFound.length)
                        return [2 /*return*/, null];
                    sortedKeysFound = keysFound.sort(function (a, b) {
                        var aVer = parseFloat(a.key);
                        var bVer = parseFloat(b.key);
                        return bVer - aVer;
                    });
                    _b = 0, sortedKeysFound_1 = sortedKeysFound;
                    _c.label = 2;
                case 2:
                    if (!(_b < sortedKeysFound_1.length)) return [3 /*break*/, 5];
                    key = sortedKeysFound_1[_b];
                    return [4 /*yield*/, promisifyFindJavaHomeInRegKey(key)];
                case 3:
                    res = _c.sent();
                    if (res) {
                        return [2 /*return*/, res];
                    }
                    _c.label = 4;
                case 4:
                    _b++;
                    return [3 /*break*/, 2];
                case 5: return [2 /*return*/, null];
            }
        });
    });
}
function promisifyFindPossibleRegKey(keyPath, regArch) {
    return new Promise(function (resolve) {
        var winreg = new winreg_1.default({
            hive: winreg_1.default.HKLM,
            key: keyPath,
            arch: regArch
        });
        winreg.keys(function (err, result) {
            if (err) {
                return resolve([]);
            }
            resolve(result);
        });
    });
}
function promisifyFindJavaHomeInRegKey(reg) {
    return new Promise(function (resolve) {
        reg.get('JavaHome', function (err, home) {
            if (err || !home) {
                return resolve(null);
            }
            resolve(home.value);
        });
    });
}
function dirIsJavaHome(dir, javaFilename) {
    return fs.existsSync('' + dir)
        && fs.statSync(dir).isDirectory()
        && fs.existsSync(path.resolve(dir, 'bin', javaFilename));
}
// iterate through symbolic links until
// file is found
function findLinkedFile(file) {
    if (!fs.lstatSync(file).isSymbolicLink())
        return file;
    return findLinkedFile(fs.readlinkSync(file));
}
module.exports = findJavaHome;
//# sourceMappingURL=index.js.map