#!/bin/sh

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

# Find the bws-secure package directory
if [ -f "$SCRIPT_DIR/../postinstall.js" ]; then
  # Direct execution from within the package
  NODE_SCRIPT="$SCRIPT_DIR/../postinstall.js"
elif [ -f "$SCRIPT_DIR/../../bws-secure/postinstall.js" ]; then
  # Execution from node_modules/.bin
  NODE_SCRIPT="$SCRIPT_DIR/../../bws-secure/postinstall.js"
else
  # Try to find it elsewhere in node_modules
  NODE_SCRIPT=$(find "$(cd "$SCRIPT_DIR/../.." && pwd)" -name "postinstall.js" -path "*/bws-secure/*" | head -n 1)
  
  # If not found, try to resolve symlinks
  if [ -z "$NODE_SCRIPT" ]; then
    # Check if bws-secure is a symlink
    if [ -L "$SCRIPT_DIR/../../bws-secure" ]; then
      # Get the real path of the symlink
      REAL_PATH=$(readlink "$SCRIPT_DIR/../../bws-secure")
      
      # Check if the path is relative
      if [[ "$REAL_PATH" != /* ]]; then
        # Convert relative path to absolute
        REAL_PATH="$(cd "$SCRIPT_DIR/../../" && cd "$REAL_PATH" && pwd)"
      fi
      
      # Check if postinstall.js exists in the real path
      if [ -f "$REAL_PATH/postinstall.js" ]; then
        NODE_SCRIPT="$REAL_PATH/postinstall.js"
      fi
    fi
  fi
  
  # If still not found, give up
  if [ -z "$NODE_SCRIPT" ]; then
    echo "\033[31mError: Cannot find bws-secure/postinstall.js script\033[0m"
    exit 1
  fi
fi

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