const fs = require('fs-extra');
const os = require("os");
const path = require('path');
const pkg = require('./package.json');

let log = (() => {
    if (["silent", "error", "warn", "http", "info", "verbose", "silly"].indexOf(process.env.npm_config_loglevel) > 3) {
        return (m) => console.log(m);
    } else {
        return () => {};
    }
})();

module.exports = (pkgHome) => {
    let pkgJsonPath = path.join(pkgHome, 'package.json');
    let distDir = path.join(pkgHome, 'dist');
    let pkgJson = require(pkgJsonPath);

    if (pkg.isInstaller) {
        log('This package contains an installer');
        let installerPath;
        let toRemove;
        log(`platform is ${process.platform}`);
        if (process.platform === "darwin") {
            toRemove = path.join(__dirname, 'dist', `SenchaCmd-${pkg.version_full}-osx.app`);
            installerPath = path.join(toRemove, 'Contents', 'MacOS');
            if (pkg.version[0] < 6) {
                installerPath = path.join(installerPath, 'installbuilder.sh');
            } else {
                installerPath = path.join(installerPath, 'JavaApplicationStub');
            }
        } else { // Assume windows, since there's no installer version for linux
            var is64Bit = process.arch === 'x64' || process.env.hasOwnProperty('PROCESSOR_ARCHITEW6432');
            installerPath = path.join(__dirname, 'dist', `SenchaCmd-${pkg.version_full}-windows-${is64Bit ? '64' : '32'}bit.exe`);
            toRemove = installerPath;
        }
        log(`Installer is at ${installerPath}`);
        log(`After installed, should remove ${toRemove}`);
        let installerArgs = [];
        if (pkg.version[0] < 6) {
            log(`BitRock mode`)
            installerArgs.push('--mode');
            installerArgs.push('unattended');
            installerArgs.push('--prefix');
            installerArgs.push(distDir);
        } else {
            log(`install4j mode`)
            installerArgs.push('-Djava.awt.headless=true');
            installerArgs.push('-Dinstall4j.nolaf=true');
            installerArgs.push('-Dinstall4j.logToStderr=true');
            installerArgs.push('-q');
            installerArgs.push('-dir');
            installerArgs.push(distDir);
            installerArgs.push('-Dall=true');
            installerArgs.push('-VnpmMode=true');
            installerArgs.push('-VaddToPath=1'); // Confusingly, addToPath is not a boolean but an array index: 0=yes, 1=no
        }
        log(`Invoking ${installerPath}`);
        log(`With arguments: '${installerArgs.join(' ')}'`)
        try {
            log(require('child_process').execFileSync(installerPath, installerArgs).toString());
        } catch (spawnRet) {
            if (spawnRet.error) {
                log('\x1b[31m\x1b[1m[ERR]\x1b[0m' + spawnRet.error.message);
            }
            if (spawnRet.stderr) {
                log('\x1b[31m\x1b[1m[ERR]\x1b[0m' + spawnRet.stderr.trim());
            }
            if (spawnRet.message) {
                log('\x1b[31m\x1b[1m[ERR]\x1b[0m' + spawnRet.message.trim());
            }
        }
    } else {
        log(`Copying dist directory`);
        fs.moveSync(path.join(__dirname, 'dist'), distDir, { overwrite: true });
    }

    log(`Removing ${__dirname}/install.js`);
    fs.removeSync(path.join(__dirname, "install.js"));
    log(`Removing ${pkgHome}/platform-install.js`);
    fs.removeSync(path.join(pkgHome, 'platform-install.js'));

    log(`Removing install hook in main package`);
    delete pkgJson.scripts.install;
    pkgJson.platformPkg = pkg.name;
    fs.outputFileSync(pkgJsonPath, JSON.stringify(pkgJson, null, 2));
};