// postinstall.js
const fs = require('fs');
const path = require('path');

const binPath = path.join(__dirname, 'backend', 'dist', 'bin');

const binaries = ['rg', 'tree'];
const permission = 0o755; // Corresponds to rwxr-xr-x

console.log('Setting executable permissions for bundled binaries...');

binaries.forEach(binaryName => {
    const binaryPath = path.join(binPath, binaryName);
    try {
        // Only attempt chmod if the binary file actually exists.
        if (fs.existsSync(binaryPath)) {
            fs.chmodSync(binaryPath, permission);
            console.log(`  ✓ Permissions set for: ${binaryPath}`);
        } else {
            // This is just a warning, not an error. The user might not have added the binaries yet.
            console.warn(`  - Warning: Binary not found, skipping: ${binaryPath}`);
        }
    } catch (error) {
        // This will catch actual errors from chmodSync, e.g., permissions issues on the host.
        console.error(`  ✗ Error setting permissions for ${binaryPath}:`, error);
        process.exit(1);
    }
});

console.log('Permissions setup complete.');