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

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

    fs.outputFileSync(path.join(__dirname, 'index.js'), [
        '// This file was intentionally left blank.',
        '// This file is used by require.resolve to property locate this module.'
    ].join('\n'));

    if (pkg.isInstaller) {
        let installerPath;
        let toRemove;
        if (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;
        }
        let installerArgs = [];
        if (pkg.version[0] < 6) {
            installerArgs.push('--mode');
            installerArgs.push('unattended');
            installerArgs.push('--prefix');
            installerArgs.push(`${path.join(__dirname, 'dist')}`);
        } else {
            installerArgs.push('-Djava.awt.headless=true');
            installerArgs.push('-Dinstall4j.nolaf=true');
            installerArgs.push('-q');
            installerArgs.push('-dir');
            installerArgs.push(`${path.join(__dirname, 'dist')}`);
            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
        }
        require('child_process').execFileSync(installerPath, installerArgs, function (err, stdout, stderr) {
            if (err) {
                console.error('\x1b[31m\x1b[1m[ERR]\x1b[0m', err.message);
            }
            if (stderr) {
                console.error('\x1b[31m\x1b[1m[ERR]\x1b[0m', stderr.trim());
            }
            xfs.removeSync(toRemove);
        });
    }

    fs.removeSync(path.join(__dirname, "install.js"));
    fs.removeSync(path.join(pkgHome, 'platform-install.js'));

    delete pkgJson.scripts.install;
    pkgJson.platformPkg = pkg.name;
    fs.outputFileSync(pkgJsonPath, JSON.stringify(pkgJson, null, 2));
};