"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.runComposerInstall = exports.getBrefFiles = void 0;
const build_utils_1 = require("@vercel/build-utils");
const child_process_1 = require("child_process");
const path_1 = __importDefault(require("path"));
const PHP_PKG = path_1.default.dirname(require.resolve('vercel-bref/package.json'));
const PHP_BIN_DIR = path_1.default.join(PHP_PKG, "native/bin");
// @ts-ignore
const PHP_BIN = path_1.default.join(PHP_BIN_DIR, "php");
const PHP_MODULES_DIR = path_1.default.join(PHP_PKG, "native/bref/lib/php/extensions/no-debug-non-zts-20200930");
const PHP_LIB_DIR = path_1.default.join(PHP_PKG, "native/bref/lib");
const PHP_LIB64_DIR = path_1.default.join(PHP_PKG, "native/bref/lib64");
const COMPOSER_BIN = path_1.default.join(PHP_BIN_DIR, "composer");
async function getBrefFiles() {
    // Lookup for all files in native folder
    return await build_utils_1.glob('native/**', { cwd: path_1.default.join(__dirname, "..") });
}
exports.getBrefFiles = getBrefFiles;
async function runComposerInstall(workPath) {
    console.log('🐘 Installing Composer dependencies [START]');
    await runPhp([
        COMPOSER_BIN,
        'install',
        '--profile',
        '--no-dev',
        '--no-interaction',
        '--no-scripts',
        '--ignore-platform-reqs',
        '--no-progress'
    ], {
        stdio: 'inherit',
        cwd: workPath
    });
    console.log('🐘 Installing Composer dependencies [DONE]');
}
exports.runComposerInstall = runComposerInstall;
async function runPhp(args, opts = {}) {
    try {
        const options = {
            ...opts,
            env: {
                ...process.env,
                ...(opts.env || {}),
                COMPOSER_HOME: '/tmp',
                PATH: `${PHP_BIN_DIR}:${process.env.PATH}`,
                PHP_INI_EXTENSION_DIR: PHP_MODULES_DIR,
                PHP_INI_SCAN_DIR: `:${path_1.default.resolve(__dirname, '../conf')}`,
                LD_LIBRARY_PATH: `${PHP_LIB_DIR}:${PHP_LIB64_DIR}:/usr/lib64:/lib64:${process.env.LD_LIBRARY_PATH}`
            }
        };
        console.log(options);
        await spawnAsync('php', args, options);
    }
    catch (e) {
        console.error(e);
        process.exit(1);
    }
}
function spawnAsync(command, args, opts = {}) {
    return new Promise((resolve, reject) => {
        const child = child_process_1.spawn(command, args, {
            stdio: "ignore",
            ...opts
        });
        child.on('error', reject);
        child.on('exit', (code, signal) => {
            if (code === 0) {
                resolve();
            }
            else {
                reject(new Error(`Exited with ${code || signal}`));
            }
        });
    });
}
