#!/bin/sh

# Get the directory where this script is located
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"

# Use Node.js to resolve the path to secureRun.js
NODE_SCRIPT=$(node -e "
const path = require('path');
const fs = require('fs');

function findSecureRunJs() {
  // Get the real path of node_modules directory
  const nodeModulesDir = path.resolve(process.cwd(), 'node_modules');
  
  const possiblePaths = [
    // Primary path - directly from node_modules
    path.join(nodeModulesDir, 'bws-secure', 'secureRun.js'),
    // Fallback - development mode
    path.join(__dirname, '..', 'secureRun.js'),
    // Fallback - from bin directory
    path.resolve(__dirname, '..', 'secureRun.js')
  ];

  console.error('Debug Info:');
  console.error('Current working directory:', process.cwd());
  console.error('Script directory:', __dirname);
  console.error('Node modules directory:', nodeModulesDir);
  console.error('Searching in paths:', possiblePaths);

  for (const p of possiblePaths) {
    console.error('Checking path:', p);
    if (fs.existsSync(p)) {
      console.error('Found secureRun.js at:', p);
      return p;
    }
  }

  console.error('\nFile not found in any location.');
  console.error('Directory contents of node_modules/bws-secure:');
  try {
    const bwsPath = path.join(nodeModulesDir, 'bws-secure');
    if (fs.existsSync(bwsPath)) {
      console.error(fs.readdirSync(bwsPath).join('\n'));
    } else {
      console.error('bws-secure directory does not exist');
    }
  } catch (err) {
    console.error('Error reading directory:', err.message);
  }
  
  throw new Error('Cannot find secureRun.js');
}

try {
  const scriptPath = findSecureRunJs();
  console.log(scriptPath);
} catch (error) {
  console.error('Error:', error.message);
  process.exit(1);
}
")

if [ $? -ne 0 ]; then
  echo "\033[31mError: Failed to locate secureRun.js\033[0m"
  echo "Current directory: $(pwd)"
  echo "Script directory: $SCRIPT_DIR"
  echo "Looking in node_modules/bws-secure"
  ls -la "$(dirname "$SCRIPT_DIR")/bws-secure" 2>/dev/null || echo "bws-secure directory not found"
  exit 1
fi

# Execute the script
node "$NODE_SCRIPT" "$@"