#!/usr/bin/env node

/**
 * Simple Shell Script Encryption
 * Encrypts .sh files to .enc files that are decrypted at runtime
 */

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

// Generate encryption key
function generateKey() {
  const pkg = require('../package.json');
  // Use only package name for consistent key across versions
  return crypto.createHash('sha256').update(pkg.name + 'devicely-encryption-key-v1').digest();
}

// Encrypt a file
function encryptFile(inputPath, outputPath) {
  const content = fs.readFileSync(inputPath, 'utf8');
  const key = generateKey();
  const iv = crypto.randomBytes(16);
  const cipher = crypto.createCipheriv('aes-256-cbc', key, iv);
  
  let encrypted = cipher.update(content, 'utf8', 'hex');
  encrypted += cipher.final('hex');
  
  const data = JSON.stringify({
    iv: iv.toString('hex'),
    content: encrypted
  });
  
  fs.writeFileSync(outputPath, data);
  console.log(`   ✓ ${path.basename(inputPath)} → ${path.basename(outputPath)}`);
}

// Encrypt all shell scripts
function encryptShellScripts(sourceDir, outputDir) {
  console.log('🔐 Encrypting shell scripts...\n');
  
  if (!fs.existsSync(outputDir)) {
    fs.mkdirSync(outputDir, { recursive: true });
  }

  const scripts = [
    'android_device_control.sh',
    'connect_android_usb_multi_final.sh',
    'connect_android_wireless.sh',
    'connect_android_wireless_multi_final.sh',
    'connect_ios_usb_multi_final.sh',
    'connect_ios_wireless_multi_final.sh',
    'ios_device_control.sh'
  ];

  let encrypted = 0;
  scripts.forEach(script => {
    const srcPath = path.join(sourceDir, script);
    if (fs.existsSync(srcPath)) {
      const encPath = path.join(outputDir, script.replace('.sh', '.enc'));
      encryptFile(srcPath, encPath);
      encrypted++;
    }
  });

  console.log(`\n✅ Encrypted ${encrypted} shell scripts\n`);
}

module.exports = { encryptShellScripts };

if (require.main === module) {
  const srcDir = path.join(__dirname, '../../');
  const outDir = path.join(__dirname, '../dist/scripts/shell');
  encryptShellScripts(srcDir, outDir);
}
