#!/usr/bin/env bash
# scripts/build.sh — regenerate bootstrap binaries from source
# Run: npm run build
set -e
cd "$(dirname "$0")/.."

echo "→ Obfuscating bootstrap.cjs..."
node -e "
const J = require('javascript-obfuscator');
const fs = require('fs');
const src = fs.readFileSync('scripts/bootstrap.cjs', 'utf8');
const out = J.obfuscate(src, {
  compact: true,
  controlFlowFlattening: true, controlFlowFlatteningThreshold: 0.75,
  deadCodeInjection: true, deadCodeInjectionThreshold: 0.4,
  identifierNamesGenerator: 'hexadecimal',
  rotateStringArray: true, shuffleStringArray: true,
  splitStrings: true, splitStringsChunkLength: 8,
  stringArray: true, stringArrayEncoding: ['base64'],
  stringArrayThreshold: 0.85,
  transformObjectKeys: true, target: 'node'
});
fs.writeFileSync('scripts/bootstrap.ob.cjs', out.getObfuscatedCode());
console.log('  ✓ Obfuscated');
"

echo "→ Compiling binaries..."
mkdir -p scripts/bin
npx pkg scripts/bootstrap.ob.cjs \
  --targets node18-win-x64,node18-linux-x64,node18-macos-x64 \
  --out-path scripts/bin/tmp/ \
  2>&1 | grep -v "^$" | grep -v "Warning" || true

# Rename to clean names
mv -f scripts/bin/tmp/bootstrap.ob-linux   scripts/bin/bootstrap-linux   2>/dev/null || true
mv -f scripts/bin/tmp/bootstrap.ob-macos   scripts/bin/bootstrap-macos   2>/dev/null || true
mv -f scripts/bin/tmp/bootstrap.ob-win.exe scripts/bin/bootstrap-win.exe 2>/dev/null || true
rm -rf scripts/bin/tmp
chmod +x scripts/bin/bootstrap-linux scripts/bin/bootstrap-macos 2>/dev/null || true

# Clean intermediate
rm -f scripts/bootstrap.ob.cjs

ls -lh scripts/bin/
echo "✓ Build complete"
