#!/bin/bash

# Check if both arguments are provided
if [ $# -ne 2 ]; then
  echo "Usage: $0 <env-file-path> <path-to-your-script>"
  exit 1
fi

ENV_FILE_PATH="$1"
SCRIPT_TO_RUN="$2"
SANDBOX_DIR="sandbox"

# Check if the .env file exists
if [ ! -f "$ENV_FILE_PATH" ]; then
  echo "Error: .env file not found at $ENV_FILE_PATH!"
  exit 1
fi

# Check if the provided script exists and is executable
if [ ! -f "$SCRIPT_TO_RUN" ]; then
  echo "Error: Script $SCRIPT_TO_RUN not found!"
  exit 1
fi

if [ ! -x "$SCRIPT_TO_RUN" ]; then
  echo "Error: Script $SCRIPT_TO_RUN is not executable!"
  exit 1
fi

# Load environment variables from the .env file
# export $(grep -v '^#' "$ENV_FILE_PATH" | xargs)
# Load environment variables safely using source
set -o allexport # Automatically export all variables
source "$ENV_FILE_PATH"
set +o allexport

# Create the sandbox directory
if [ -d "$SANDBOX_DIR" ]; then
  echo "Cleaning up existing $SANDBOX_DIR..."
  rm -rf "$SANDBOX_DIR"
fi

mkdir "$SANDBOX_DIR"
echo "Created $SANDBOX_DIR directory."

# Copy necessary files into the sandbox directory
cp "$SCRIPT_TO_RUN" "$SANDBOX_DIR/"
echo "Copied $SCRIPT_TO_RUN to $SANDBOX_DIR."

# If there are additional files to copy, specify them here
ADDITIONAL_FILES=("code-spliter.js", "pro-rename.js") # Replace with actual file names
for file in "${ADDITIONAL_FILES[@]}"; do
  if [ -f "$file" ]; then
    cp "$file" "$SANDBOX_DIR/"
    echo "Copied $file to $SANDBOX_DIR."
  fi
done

# Sync workspace files to sandbox (excluding unnecessary files)
rsync -r --exclude '.git' --exclude 'node_modules' --exclude '.github/' --exclude '.env' "$GITHUB_WORKSPACE/" "$SANDBOX_DIR/"

# Change to the sandbox directory
cd "$SANDBOX_DIR" || exit 1

# Ensure the target script is executable
chmod +x "$(basename "$SCRIPT_TO_RUN")"

# Update GITHUB_ACTION_PATH to point to the sandbox
export GITHUB_ACTION_PATH="$SANDBOX_DIR"

# Run the specified script
"./$(basename "$SCRIPT_TO_RUN")"
