#!/usr/bin/env node
/**
 * Post-install script to set executable permissions on Linux binaries
 * and check for required system dependencies
 */

import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import { execSync } from 'child_process';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

function detectDistro(): string {
    if (!fs.existsSync('/etc/os-release')) {
        return 'unknown';
    }

    try {
        const osRelease = fs.readFileSync('/etc/os-release', 'utf8').toLowerCase();

        if (osRelease.includes('ubuntu') || osRelease.includes('debian')) {
            return 'debian';
        }
        if (osRelease.includes('fedora') || osRelease.includes('rhel') || osRelease.includes('centos')) {
            return 'fedora';
        }
        if (osRelease.includes('arch')) {
            return 'arch';
        }

        return 'unknown';
    } catch {
        return 'unknown';
    }
}

function showDependencyInstallCommand(distro: string): void {
    console.warn('\n⚠️  Missing system dependencies detected!');
    console.warn('   Install required libraries with:\n');

    switch (distro) {
        case 'debian':
            console.warn('   sudo apt update');
            console.warn('   sudo apt install libwebkit2gtk-4.1-0 libgtk-3-0\n');
            break;
        case 'fedora':
            console.warn('   sudo dnf install webkit2gtk4.1 gtk3\n');
            break;
        case 'arch':
            console.warn('   sudo pacman -S webkit2gtk gtk3\n');
            break;
        default:
            console.warn('   Install webkit2gtk and gtk3 for your distribution\n');
    }
}

function checkSystemDependencies(binaryPath: string): void {
    try {
        const lddOutput = execSync(`ldd "${binaryPath}" 2>&1`, { encoding: 'utf8' });

        if (lddOutput.includes('not found')) {
            const distro = detectDistro();
            showDependencyInstallCommand(distro);
        }
    } catch {
        // ldd command failed or not installed - skip check
    }
}

function setExecutePermissions(binaryPath: string, binaryName: string): void {
    try {
        fs.chmodSync(binaryPath, 0o755);
        console.log(`✅ Set execute permissions on ${binaryName} binary`);
    } catch (error: any) {
        console.warn(`⚠️  Could not set execute permission on ${binaryPath}: ${error.message}`);
        console.warn(`   You may need to run: sudo chmod +x ${binaryPath}`);
    }
}

function main(): void {
    // Windows doesn't need executable permissions
    if (process.platform === 'win32') {
        return;
    }

    // Determine binary name based on architecture
    const arch = process.arch;
    const binaryName = arch === 'arm64' ? 'msgernative-linux-aarch64' : 'msgernative';
    const binaryPath = path.join(__dirname, '..', 'bin', binaryName);

    // Binary doesn't exist - warn user
    if (!fs.existsSync(binaryPath)) {
        console.warn(`⚠️  Binary not found at ${binaryPath}`);
        console.warn(`   The msger package may not support your platform (${process.platform} ${arch})`);
        return;
    }

    // Set executable permissions
    setExecutePermissions(binaryPath, binaryName);

    // Check for required system libraries
    checkSystemDependencies(binaryPath);
}

main();
