#!/bin/sh

# BWS Installer
echo "🔒 BWS Secure initialization script running..."

# Get directory of this script
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"

# Get project root (where the package.json is)
# This should be the cwd when running the script
PROJ_ROOT="$(pwd)"

# Make sure we can find the node_modules directory
if [ ! -d "$PROJ_ROOT/node_modules" ]; then
  # Try going up until we find node_modules or reach filesystem root
  current="$PROJ_ROOT"
  while [ "$current" != "/" ] && [ ! -d "$current/node_modules" ]; do
    current="$(dirname "$current")"
  done
  
  if [ -d "$current/node_modules" ]; then
    PROJ_ROOT="$current"
  fi
fi

echo "Project root: $PROJ_ROOT"
echo "Script directory: $SCRIPT_DIR"

# Create symbolic links for the CLI commands in node_modules/.bin
BIN_DIR="${PROJ_ROOT}/node_modules/.bin"
mkdir -p "$BIN_DIR"

# Create symlinks for all binaries
echo "Creating symlinks for BWS binaries..."

# Create symlinks for each binary using a simple loop
create_symlink() {
  bin_name="$1"
  source_path="$2"
  
  source_file="${SCRIPT_DIR}/${source_path}"
  target_file="${BIN_DIR}/${bin_name}"
  
  # Create symlink
  ln -sf "$source_file" "$target_file"
  
  # Ensure the source file is executable
  chmod +x "$source_file" 2>/dev/null || true
  
  echo "Created symlink for $bin_name"
}

# Create symlinks matching package.json bin field
create_symlink "secure-run" "bin/secure-run"
create_symlink "bws-list" "bin/bws-list"
create_symlink "bws-upload" "bin/bws-upload"
create_symlink "bws-scan" "bin/bws-scan"
create_symlink "bws-setup" "bin/bws-setup"

echo "✅ BWS Secure installation complete!"
