#!/usr/bin/env node
/**
 * npm postinstall script for @netwan/lava
 * 设置 Linux/macOS 平台二进制文件的执行权限
 */

const fs = require('fs');
const path = require('path');

const platform = process.platform;

// Windows 不需要设置权限
if (platform === 'win32') {
  console.log('Windows platform detected, skipping chmod');
  process.exit(0);
}

const scriptDir = __dirname;
const binariesDir = path.join(scriptDir, 'binaries');

// 要设置权限的二进制文件
const binaries = ['lc', 'lpp', 'lvm1', 'lvm2'];

// 当前平台目录
let platformDir;
const arch = process.arch;

switch (platform) {
  case 'linux':
    platformDir = arch === 'arm64' ? 'linux-arm64' : 'linux-x64';
    break;
  case 'darwin':
    platformDir = `darwin-${arch}`;
    break;
  default:
    console.log(`Platform ${platform} not supported, skipping`);
    process.exit(0);
}

const targetDir = path.join(binariesDir, platformDir);

if (!fs.existsSync(targetDir)) {
  console.log(`Target directory not found: ${targetDir}`);
  process.exit(0);
}

console.log(`Setting execute permissions for ${platformDir}...`);

let fixedCount = 0;

for (const bin of binaries) {
  const binFile = path.join(targetDir, bin);

  if (!fs.existsSync(binFile)) {
    continue;
  }

  try {
    const stats = fs.statSync(binFile);
    const mode = stats.mode;
    const hasExecPerm = (mode & 0o111) !== 0;

    if (!hasExecPerm) {
      fs.chmodSync(binFile, '755');
      console.log(`  Fixed: ${bin}`);
      fixedCount++;
    }
  } catch (err) {
    console.log(`  Error: ${bin} - ${err.message}`);
  }
}

if (fixedCount > 0) {
  console.log(`Permissions fixed for ${fixedCount} file(s)`);
} else {
  console.log('All files already have execute permissions');
}
