#!/bin/bash

#Run it: ./shell/build.sh

# Set error handling
set -e

# Get the directory of the script
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )"

# Navigate to the plugin root directory
PLUGIN_ROOT="$(dirname "$SCRIPT_DIR")"
cd "$PLUGIN_ROOT"

# Define output directory as current directory
OUTPUT_DIR="$PLUGIN_ROOT"

# Plugin name
PLUGIN_NAME="image-background-remover"

# Temporary directory for zip creation
TEMP_DIR=$(mktemp -d)

# Function to clean up temporary directory
cleanup() {
    rm -rf "$TEMP_DIR"
    echo "Temporary directory cleaned up."
}

# Trap to ensure cleanup happens even if script fails
trap cleanup EXIT

# Copy plugin files to temporary directory
echo "Copying plugin files..."
cp -R . "$TEMP_DIR/$PLUGIN_NAME"

# Remove unnecessary files and directories
echo "Removing unnecessary files..."
rm -rf "$TEMP_DIR/$PLUGIN_NAME/.git"
rm -rf "$TEMP_DIR/$PLUGIN_NAME/.gitignore"
rm -rf "$TEMP_DIR/$PLUGIN_NAME/shell"
find "$TEMP_DIR/$PLUGIN_NAME" -name ".DS_Store" -delete

# Create zip file
echo "Creating zip file..."
cd "$TEMP_DIR"
zip -r "$OUTPUT_DIR/$PLUGIN_NAME.zip" "$PLUGIN_NAME"

# Verify zip file
if [ -f "$OUTPUT_DIR/$PLUGIN_NAME.zip" ]; then
    echo "Successfully created $PLUGIN_NAME.zip at $OUTPUT_DIR"
    echo "Zip file size: $(du -h "$OUTPUT_DIR/$PLUGIN_NAME.zip" | cut -f1)"
else
    echo "Failed to create zip file"
    exit 1
fi